From 4bfda1cc9abc03127094e4fd81490bcfd4b7389b Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 27 Sep 2026 04:18:16 +0800 Subject: [PATCH] Integrate Venix sales portal with private libvirt engine --- .gitignore | 4 + AGENTS.md | 11 +- README.md | 53 +- deploy/virt-cloud-engine.service | 25 + deploy/virt-cloud-worker.service | 25 + docs/DEPLOYMENT.md | 150 + docs/INTEGRATION_PLAN.md | 178 +- docs/VALIDATION.md | 26 + engine/.gitignore | 5 + engine/requirements-dev.txt | 3 + engine/requirements.txt | 8 + engine/static/almalinux-icon.svg | 25 + engine/static/app.js | 4090 +++++++++++++++++ engine/static/centos-icon.svg | 1 + engine/static/debian-icon.svg | 51 + engine/static/index.html | 493 ++ engine/static/styles.css | 193 + engine/static/ubuntu-icon.svg | 1 + engine/static/vendor/novnc/LICENSE.txt | 62 + engine/static/vendor/novnc/core/base64.js | 104 + engine/static/vendor/novnc/core/crypto/aes.js | 178 + .../static/vendor/novnc/core/crypto/bigint.js | 34 + .../static/vendor/novnc/core/crypto/crypto.js | 90 + engine/static/vendor/novnc/core/crypto/des.js | 330 ++ engine/static/vendor/novnc/core/crypto/dh.js | 55 + engine/static/vendor/novnc/core/crypto/md5.js | 82 + engine/static/vendor/novnc/core/crypto/rsa.js | 132 + .../vendor/novnc/core/decoders/copyrect.js | 27 + .../static/vendor/novnc/core/decoders/h264.js | 321 ++ .../vendor/novnc/core/decoders/hextile.js | 181 + .../static/vendor/novnc/core/decoders/jpeg.js | 161 + .../static/vendor/novnc/core/decoders/raw.js | 59 + .../static/vendor/novnc/core/decoders/rre.js | 44 + .../vendor/novnc/core/decoders/tight.js | 393 ++ .../vendor/novnc/core/decoders/tightpng.js | 27 + .../static/vendor/novnc/core/decoders/zlib.js | 51 + .../static/vendor/novnc/core/decoders/zrle.js | 185 + engine/static/vendor/novnc/core/deflator.js | 84 + engine/static/vendor/novnc/core/display.js | 578 +++ engine/static/vendor/novnc/core/encodings.js | 54 + engine/static/vendor/novnc/core/inflator.js | 65 + .../vendor/novnc/core/input/domkeytable.js | 311 ++ .../vendor/novnc/core/input/fixedkeys.js | 129 + .../vendor/novnc/core/input/gesturehandler.js | 567 +++ .../vendor/novnc/core/input/keyboard.js | 294 ++ .../static/vendor/novnc/core/input/keysym.js | 616 +++ .../vendor/novnc/core/input/keysymdef.js | 688 +++ engine/static/vendor/novnc/core/input/util.js | 191 + .../static/vendor/novnc/core/input/vkeys.js | 116 + .../vendor/novnc/core/input/xtscancodes.js | 173 + engine/static/vendor/novnc/core/ra2.js | 312 ++ engine/static/vendor/novnc/core/rfb.js | 3411 ++++++++++++++ .../static/vendor/novnc/core/util/browser.js | 233 + .../static/vendor/novnc/core/util/cursor.js | 249 + .../static/vendor/novnc/core/util/element.js | 32 + .../static/vendor/novnc/core/util/events.js | 138 + .../vendor/novnc/core/util/eventtarget.js | 35 + engine/static/vendor/novnc/core/util/int.js | 15 + .../static/vendor/novnc/core/util/logging.js | 56 + .../static/vendor/novnc/core/util/strings.js | 28 + engine/static/vendor/novnc/core/websock.js | 369 ++ .../static/vendor/novnc/vendor/pako/LICENSE | 21 + .../static/vendor/novnc/vendor/pako/README.md | 6 + .../novnc/vendor/pako/lib/utils/common.js | 45 + .../novnc/vendor/pako/lib/zlib/adler32.js | 27 + .../novnc/vendor/pako/lib/zlib/constants.js | 47 + .../novnc/vendor/pako/lib/zlib/crc32.js | 36 + .../novnc/vendor/pako/lib/zlib/deflate.js | 1846 ++++++++ .../novnc/vendor/pako/lib/zlib/gzheader.js | 35 + .../novnc/vendor/pako/lib/zlib/inffast.js | 324 ++ .../novnc/vendor/pako/lib/zlib/inflate.js | 1527 ++++++ .../novnc/vendor/pako/lib/zlib/inftrees.js | 322 ++ .../novnc/vendor/pako/lib/zlib/messages.js | 11 + .../novnc/vendor/pako/lib/zlib/trees.js | 1195 +++++ .../novnc/vendor/pako/lib/zlib/zstream.js | 24 + engine/tests/test_app.py | 1649 +++++++ engine/tests/test_auth_sessions.py | 79 + engine/tests/test_cloud_init.py | 230 + engine/tests/test_cloud_templates.py | 181 + engine/tests/test_config.py | 31 + engine/tests/test_console.py | 199 + engine/tests/test_database.py | 517 +++ engine/tests/test_database_bootstrap.py | 84 + engine/tests/test_database_http.py | 439 ++ engine/tests/test_engine_boundary.py | 413 ++ engine/tests/test_frontend_page_layout.py | 200 + engine/tests/test_libvirt_service.py | 2287 +++++++++ engine/tests/test_metrics.py | 470 ++ engine/tests/test_panel_state.py | 111 + engine/tests/test_public_ip_pool.py | 112 + engine/tests/test_registration_http.py | 982 ++++ engine/tests/test_remote_host.py | 561 +++ engine/tests/test_rescue_templates.py | 71 + engine/tests/test_smtp_service.py | 201 + engine/tests/test_ssh_agent.py | 210 + engine/tests/test_ssh_keys.py | 168 + engine/tests/test_template_frontend.py | 218 + engine/tests/test_update_worker.py | 80 + engine/tests/test_updater.py | 255 + engine/tests/test_users.py | 253 + engine/virsh_panel/__init__.py | 1 + engine/virsh_panel/app.py | 2532 ++++++++++ engine/virsh_panel/auth.py | 188 + engine/virsh_panel/cloud_init.py | 362 ++ engine/virsh_panel/cloud_templates.py | 273 ++ engine/virsh_panel/config.py | 43 + engine/virsh_panel/console.py | 195 + engine/virsh_panel/database.py | 994 ++++ engine/virsh_panel/database_bootstrap.py | 237 + engine/virsh_panel/engine_context.py | 213 + engine/virsh_panel/engine_security.py | 100 + engine/virsh_panel/internal.py | 655 +++ engine/virsh_panel/libvirt_service.py | 1955 ++++++++ engine/virsh_panel/metrics.py | 278 ++ engine/virsh_panel/panel_state.py | 186 + engine/virsh_panel/remote_host.py | 825 ++++ engine/virsh_panel/rescue_templates.py | 151 + engine/virsh_panel/smtp_service.py | 215 + engine/virsh_panel/ssh_agent.py | 371 ++ engine/virsh_panel/ssh_keys.py | 165 + engine/virsh_panel/update_worker.py | 109 + engine/virsh_panel/updater.py | 539 +++ engine/virsh_panel/users.py | 497 ++ web/.gitignore | 2 +- web/app/Command/CloudSetup.php | 154 + web/app/Command/CloudWorker.php | 28 + web/app/Command/XCat.php | 6 + .../Controllers/Admin/CloudPageController.php | 34 + web/app/Controllers/Admin/ShopController.php | 12 +- web/app/Controllers/AuthController.php | 24 +- web/app/Controllers/CloudAdminController.php | 173 + web/app/Controllers/CloudApiController.php | 297 ++ .../Controllers/CloudInternalController.php | 60 + web/app/Controllers/CloudPageController.php | 15 + web/app/Middleware/CloudApi.php | 31 + web/app/Models/CloudHost.php | 8 + web/app/Models/CloudInstance.php | 8 + web/app/Models/CloudJob.php | 8 + web/app/Models/CloudOrder.php | 9 + web/app/Models/CloudSSHKey.php | 7 + web/app/Models/CloudSession.php | 11 + web/app/Models/Shop.php | 11 + web/app/Services/Auth.php | 1 + web/app/Services/Cloud/CloudAccess.php | 58 + web/app/Services/Cloud/CloudEngineClient.php | 111 + web/app/Services/Cloud/CloudError.php | 10 + web/app/Services/Cloud/CloudInput.php | 75 + web/app/Services/Cloud/CloudJobService.php | 45 + web/app/Services/Cloud/CloudMoney.php | 24 + web/app/Services/Cloud/CloudOrderService.php | 128 + web/app/Services/Cloud/CloudSSHKeys.php | 43 + web/app/Services/Cloud/CloudSecrets.php | 57 + .../Services/Cloud/CloudSessionService.php | 125 + web/app/Services/Cloud/CloudWorkerService.php | 182 + web/app/Services/Config.php | 33 +- web/app/Services/Mail/Smtp.php | 6 +- web/app/Services/UserDataDeletionService.php | 14 + web/bootstrap.php | 6 +- web/config/.config.php.example | 18 + web/config/routes.php | 19 +- web/config/routes_cloud.php | 37 + web/public/cloud/account.css | 76 + web/public/cloud/admin.css | 12 + web/public/cloud/admin.js | 90 + web/public/cloud/almalinux-icon.svg | 25 + web/public/cloud/app.js | 742 +++ web/public/cloud/centos-icon.svg | 1 + web/public/cloud/client.css | 2 + web/public/cloud/debian-icon.svg | 51 + web/public/cloud/styles.css | 193 + web/public/cloud/ubuntu-icon.svg | 1 + web/public/cloud/vendor/novnc/LICENSE.txt | 62 + web/public/cloud/vendor/novnc/core/base64.js | 104 + .../cloud/vendor/novnc/core/crypto/aes.js | 178 + .../cloud/vendor/novnc/core/crypto/bigint.js | 34 + .../cloud/vendor/novnc/core/crypto/crypto.js | 90 + .../cloud/vendor/novnc/core/crypto/des.js | 330 ++ .../cloud/vendor/novnc/core/crypto/dh.js | 55 + .../cloud/vendor/novnc/core/crypto/md5.js | 82 + .../cloud/vendor/novnc/core/crypto/rsa.js | 132 + .../vendor/novnc/core/decoders/copyrect.js | 27 + .../cloud/vendor/novnc/core/decoders/h264.js | 321 ++ .../vendor/novnc/core/decoders/hextile.js | 181 + .../cloud/vendor/novnc/core/decoders/jpeg.js | 161 + .../cloud/vendor/novnc/core/decoders/raw.js | 59 + .../cloud/vendor/novnc/core/decoders/rre.js | 44 + .../cloud/vendor/novnc/core/decoders/tight.js | 393 ++ .../vendor/novnc/core/decoders/tightpng.js | 27 + .../cloud/vendor/novnc/core/decoders/zlib.js | 51 + .../cloud/vendor/novnc/core/decoders/zrle.js | 185 + .../cloud/vendor/novnc/core/deflator.js | 84 + web/public/cloud/vendor/novnc/core/display.js | 578 +++ .../cloud/vendor/novnc/core/encodings.js | 54 + .../cloud/vendor/novnc/core/inflator.js | 65 + .../vendor/novnc/core/input/domkeytable.js | 311 ++ .../vendor/novnc/core/input/fixedkeys.js | 129 + .../vendor/novnc/core/input/gesturehandler.js | 567 +++ .../cloud/vendor/novnc/core/input/keyboard.js | 294 ++ .../cloud/vendor/novnc/core/input/keysym.js | 616 +++ .../vendor/novnc/core/input/keysymdef.js | 688 +++ .../cloud/vendor/novnc/core/input/util.js | 191 + .../cloud/vendor/novnc/core/input/vkeys.js | 116 + .../vendor/novnc/core/input/xtscancodes.js | 173 + web/public/cloud/vendor/novnc/core/ra2.js | 312 ++ web/public/cloud/vendor/novnc/core/rfb.js | 3411 ++++++++++++++ .../cloud/vendor/novnc/core/util/browser.js | 233 + .../cloud/vendor/novnc/core/util/cursor.js | 249 + .../cloud/vendor/novnc/core/util/element.js | 32 + .../cloud/vendor/novnc/core/util/events.js | 138 + .../vendor/novnc/core/util/eventtarget.js | 35 + .../cloud/vendor/novnc/core/util/int.js | 15 + .../cloud/vendor/novnc/core/util/logging.js | 56 + .../cloud/vendor/novnc/core/util/strings.js | 28 + web/public/cloud/vendor/novnc/core/websock.js | 369 ++ .../cloud/vendor/novnc/vendor/pako/LICENSE | 21 + .../cloud/vendor/novnc/vendor/pako/README.md | 6 + .../novnc/vendor/pako/lib/utils/common.js | 45 + .../novnc/vendor/pako/lib/zlib/adler32.js | 27 + .../novnc/vendor/pako/lib/zlib/constants.js | 47 + .../novnc/vendor/pako/lib/zlib/crc32.js | 36 + .../novnc/vendor/pako/lib/zlib/deflate.js | 1846 ++++++++ .../novnc/vendor/pako/lib/zlib/gzheader.js | 35 + .../novnc/vendor/pako/lib/zlib/inffast.js | 324 ++ .../novnc/vendor/pako/lib/zlib/inflate.js | 1527 ++++++ .../novnc/vendor/pako/lib/zlib/inftrees.js | 322 ++ .../novnc/vendor/pako/lib/zlib/messages.js | 11 + .../novnc/vendor/pako/lib/zlib/trees.js | 1195 +++++ .../novnc/vendor/pako/lib/zlib/zstream.js | 24 + .../views/venix/admin/cloud/instances.tpl | 2 + .../views/venix/admin/cloud/orders.tpl | 2 + .../views/venix/admin/cloud/rescue.tpl | 4 + .../views/venix/admin/cloud/templates.tpl | 5 + .../views/venix/admin/hosts/index.tpl | 28 +- .../views/venix/admin/hosts/preparation.tpl | 20 - .../views/venix/admin/shop/create.tpl | 3 +- web/resources/views/venix/admin/shop/edit.tpl | 3 +- .../views/venix/admin/shop/form_js.tpl | 24 +- .../views/venix/admin/static_header.tpl | 4 + .../views/venix/auth/layout_header.tpl | 7 +- web/resources/views/venix/cloud/index.tpl | 140 + .../views/venix/user/bought_invoice.tpl | 6 +- .../views/venix/user/layout_header.tpl | 12 +- .../views/venix/user/layout_plain_header.tpl | 3 +- web/sql/cloud.sql | 89 + web/sql/cloud_log.sql | 2 + web/sql/ss.sql | 1 + web/tests/CloudFinancialWorkflowTest.php | 121 + web/tests/CloudProtocolTest.php | 46 + web/tests/CloudSecretsTest.php | 28 + web/tests/CloudSessionSecurityTest.php | 91 + web/tests/PrunedProjectContractTest.php | 4 +- web/tests/RouteTargetTest.php | 3 +- web/tests/VirtualizationAssetsTest.php | 35 + web/tests/VirtualizationConfigTest.php | 40 + web/tests/VirtualizationLoginBoundaryTest.php | 16 + web/tests/VirtualizationSetupExportTest.php | 45 + 256 files changed, 63518 insertions(+), 228 deletions(-) create mode 100644 deploy/virt-cloud-engine.service create mode 100644 deploy/virt-cloud-worker.service create mode 100644 docs/DEPLOYMENT.md create mode 100644 docs/VALIDATION.md create mode 100644 engine/.gitignore create mode 100644 engine/requirements-dev.txt create mode 100644 engine/requirements.txt create mode 100644 engine/static/almalinux-icon.svg create mode 100644 engine/static/app.js create mode 100644 engine/static/centos-icon.svg create mode 100644 engine/static/debian-icon.svg create mode 100644 engine/static/index.html create mode 100644 engine/static/styles.css create mode 100644 engine/static/ubuntu-icon.svg create mode 100644 engine/static/vendor/novnc/LICENSE.txt create mode 100644 engine/static/vendor/novnc/core/base64.js create mode 100644 engine/static/vendor/novnc/core/crypto/aes.js create mode 100644 engine/static/vendor/novnc/core/crypto/bigint.js create mode 100644 engine/static/vendor/novnc/core/crypto/crypto.js create mode 100644 engine/static/vendor/novnc/core/crypto/des.js create mode 100644 engine/static/vendor/novnc/core/crypto/dh.js create mode 100644 engine/static/vendor/novnc/core/crypto/md5.js create mode 100644 engine/static/vendor/novnc/core/crypto/rsa.js create mode 100644 engine/static/vendor/novnc/core/decoders/copyrect.js create mode 100644 engine/static/vendor/novnc/core/decoders/h264.js create mode 100644 engine/static/vendor/novnc/core/decoders/hextile.js create mode 100644 engine/static/vendor/novnc/core/decoders/jpeg.js create mode 100644 engine/static/vendor/novnc/core/decoders/raw.js create mode 100644 engine/static/vendor/novnc/core/decoders/rre.js create mode 100644 engine/static/vendor/novnc/core/decoders/tight.js create mode 100644 engine/static/vendor/novnc/core/decoders/tightpng.js create mode 100644 engine/static/vendor/novnc/core/decoders/zlib.js create mode 100644 engine/static/vendor/novnc/core/decoders/zrle.js create mode 100644 engine/static/vendor/novnc/core/deflator.js create mode 100644 engine/static/vendor/novnc/core/display.js create mode 100644 engine/static/vendor/novnc/core/encodings.js create mode 100644 engine/static/vendor/novnc/core/inflator.js create mode 100644 engine/static/vendor/novnc/core/input/domkeytable.js create mode 100644 engine/static/vendor/novnc/core/input/fixedkeys.js create mode 100644 engine/static/vendor/novnc/core/input/gesturehandler.js create mode 100644 engine/static/vendor/novnc/core/input/keyboard.js create mode 100644 engine/static/vendor/novnc/core/input/keysym.js create mode 100644 engine/static/vendor/novnc/core/input/keysymdef.js create mode 100644 engine/static/vendor/novnc/core/input/util.js create mode 100644 engine/static/vendor/novnc/core/input/vkeys.js create mode 100644 engine/static/vendor/novnc/core/input/xtscancodes.js create mode 100644 engine/static/vendor/novnc/core/ra2.js create mode 100644 engine/static/vendor/novnc/core/rfb.js create mode 100644 engine/static/vendor/novnc/core/util/browser.js create mode 100644 engine/static/vendor/novnc/core/util/cursor.js create mode 100644 engine/static/vendor/novnc/core/util/element.js create mode 100644 engine/static/vendor/novnc/core/util/events.js create mode 100644 engine/static/vendor/novnc/core/util/eventtarget.js create mode 100644 engine/static/vendor/novnc/core/util/int.js create mode 100644 engine/static/vendor/novnc/core/util/logging.js create mode 100644 engine/static/vendor/novnc/core/util/strings.js create mode 100644 engine/static/vendor/novnc/core/websock.js create mode 100644 engine/static/vendor/novnc/vendor/pako/LICENSE create mode 100644 engine/static/vendor/novnc/vendor/pako/README.md create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/utils/common.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/adler32.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/constants.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/crc32.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/deflate.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/gzheader.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/inffast.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/inflate.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/inftrees.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/messages.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/trees.js create mode 100644 engine/static/vendor/novnc/vendor/pako/lib/zlib/zstream.js create mode 100644 engine/tests/test_app.py create mode 100644 engine/tests/test_auth_sessions.py create mode 100644 engine/tests/test_cloud_init.py create mode 100644 engine/tests/test_cloud_templates.py create mode 100644 engine/tests/test_config.py create mode 100644 engine/tests/test_console.py create mode 100644 engine/tests/test_database.py create mode 100644 engine/tests/test_database_bootstrap.py create mode 100644 engine/tests/test_database_http.py create mode 100644 engine/tests/test_engine_boundary.py create mode 100644 engine/tests/test_frontend_page_layout.py create mode 100644 engine/tests/test_libvirt_service.py create mode 100644 engine/tests/test_metrics.py create mode 100644 engine/tests/test_panel_state.py create mode 100644 engine/tests/test_public_ip_pool.py create mode 100644 engine/tests/test_registration_http.py create mode 100644 engine/tests/test_remote_host.py create mode 100644 engine/tests/test_rescue_templates.py create mode 100644 engine/tests/test_smtp_service.py create mode 100644 engine/tests/test_ssh_agent.py create mode 100644 engine/tests/test_ssh_keys.py create mode 100644 engine/tests/test_template_frontend.py create mode 100644 engine/tests/test_update_worker.py create mode 100644 engine/tests/test_updater.py create mode 100644 engine/tests/test_users.py create mode 100644 engine/virsh_panel/__init__.py create mode 100644 engine/virsh_panel/app.py create mode 100644 engine/virsh_panel/auth.py create mode 100644 engine/virsh_panel/cloud_init.py create mode 100644 engine/virsh_panel/cloud_templates.py create mode 100644 engine/virsh_panel/config.py create mode 100644 engine/virsh_panel/console.py create mode 100644 engine/virsh_panel/database.py create mode 100644 engine/virsh_panel/database_bootstrap.py create mode 100644 engine/virsh_panel/engine_context.py create mode 100644 engine/virsh_panel/engine_security.py create mode 100644 engine/virsh_panel/internal.py create mode 100644 engine/virsh_panel/libvirt_service.py create mode 100644 engine/virsh_panel/metrics.py create mode 100644 engine/virsh_panel/panel_state.py create mode 100644 engine/virsh_panel/remote_host.py create mode 100644 engine/virsh_panel/rescue_templates.py create mode 100644 engine/virsh_panel/smtp_service.py create mode 100644 engine/virsh_panel/ssh_agent.py create mode 100644 engine/virsh_panel/ssh_keys.py create mode 100644 engine/virsh_panel/update_worker.py create mode 100644 engine/virsh_panel/updater.py create mode 100644 engine/virsh_panel/users.py create mode 100644 web/app/Command/CloudSetup.php create mode 100644 web/app/Command/CloudWorker.php create mode 100644 web/app/Controllers/Admin/CloudPageController.php create mode 100644 web/app/Controllers/CloudAdminController.php create mode 100644 web/app/Controllers/CloudApiController.php create mode 100644 web/app/Controllers/CloudInternalController.php create mode 100644 web/app/Controllers/CloudPageController.php create mode 100644 web/app/Middleware/CloudApi.php create mode 100644 web/app/Models/CloudHost.php create mode 100644 web/app/Models/CloudInstance.php create mode 100644 web/app/Models/CloudJob.php create mode 100644 web/app/Models/CloudOrder.php create mode 100644 web/app/Models/CloudSSHKey.php create mode 100644 web/app/Models/CloudSession.php create mode 100644 web/app/Services/Cloud/CloudAccess.php create mode 100644 web/app/Services/Cloud/CloudEngineClient.php create mode 100644 web/app/Services/Cloud/CloudError.php create mode 100644 web/app/Services/Cloud/CloudInput.php create mode 100644 web/app/Services/Cloud/CloudJobService.php create mode 100644 web/app/Services/Cloud/CloudMoney.php create mode 100644 web/app/Services/Cloud/CloudOrderService.php create mode 100644 web/app/Services/Cloud/CloudSSHKeys.php create mode 100644 web/app/Services/Cloud/CloudSecrets.php create mode 100644 web/app/Services/Cloud/CloudSessionService.php create mode 100644 web/app/Services/Cloud/CloudWorkerService.php create mode 100644 web/config/routes_cloud.php create mode 100644 web/public/cloud/account.css create mode 100644 web/public/cloud/admin.css create mode 100644 web/public/cloud/admin.js create mode 100644 web/public/cloud/almalinux-icon.svg create mode 100644 web/public/cloud/app.js create mode 100644 web/public/cloud/centos-icon.svg create mode 100644 web/public/cloud/client.css create mode 100644 web/public/cloud/debian-icon.svg create mode 100644 web/public/cloud/styles.css create mode 100644 web/public/cloud/ubuntu-icon.svg create mode 100644 web/public/cloud/vendor/novnc/LICENSE.txt create mode 100644 web/public/cloud/vendor/novnc/core/base64.js create mode 100644 web/public/cloud/vendor/novnc/core/crypto/aes.js create mode 100644 web/public/cloud/vendor/novnc/core/crypto/bigint.js create mode 100644 web/public/cloud/vendor/novnc/core/crypto/crypto.js create mode 100644 web/public/cloud/vendor/novnc/core/crypto/des.js create mode 100644 web/public/cloud/vendor/novnc/core/crypto/dh.js create mode 100644 web/public/cloud/vendor/novnc/core/crypto/md5.js create mode 100644 web/public/cloud/vendor/novnc/core/crypto/rsa.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/copyrect.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/h264.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/hextile.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/jpeg.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/raw.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/rre.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/tight.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/tightpng.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/zlib.js create mode 100644 web/public/cloud/vendor/novnc/core/decoders/zrle.js create mode 100644 web/public/cloud/vendor/novnc/core/deflator.js create mode 100644 web/public/cloud/vendor/novnc/core/display.js create mode 100644 web/public/cloud/vendor/novnc/core/encodings.js create mode 100644 web/public/cloud/vendor/novnc/core/inflator.js create mode 100644 web/public/cloud/vendor/novnc/core/input/domkeytable.js create mode 100644 web/public/cloud/vendor/novnc/core/input/fixedkeys.js create mode 100644 web/public/cloud/vendor/novnc/core/input/gesturehandler.js create mode 100644 web/public/cloud/vendor/novnc/core/input/keyboard.js create mode 100644 web/public/cloud/vendor/novnc/core/input/keysym.js create mode 100644 web/public/cloud/vendor/novnc/core/input/keysymdef.js create mode 100644 web/public/cloud/vendor/novnc/core/input/util.js create mode 100644 web/public/cloud/vendor/novnc/core/input/vkeys.js create mode 100644 web/public/cloud/vendor/novnc/core/input/xtscancodes.js create mode 100644 web/public/cloud/vendor/novnc/core/ra2.js create mode 100644 web/public/cloud/vendor/novnc/core/rfb.js create mode 100644 web/public/cloud/vendor/novnc/core/util/browser.js create mode 100644 web/public/cloud/vendor/novnc/core/util/cursor.js create mode 100644 web/public/cloud/vendor/novnc/core/util/element.js create mode 100644 web/public/cloud/vendor/novnc/core/util/events.js create mode 100644 web/public/cloud/vendor/novnc/core/util/eventtarget.js create mode 100644 web/public/cloud/vendor/novnc/core/util/int.js create mode 100644 web/public/cloud/vendor/novnc/core/util/logging.js create mode 100644 web/public/cloud/vendor/novnc/core/util/strings.js create mode 100644 web/public/cloud/vendor/novnc/core/websock.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/LICENSE create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/README.md create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/utils/common.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/adler32.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/constants.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/crc32.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/deflate.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/gzheader.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inffast.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inflate.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inftrees.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/messages.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/trees.js create mode 100644 web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/zstream.js create mode 100644 web/resources/views/venix/admin/cloud/instances.tpl create mode 100644 web/resources/views/venix/admin/cloud/orders.tpl create mode 100644 web/resources/views/venix/admin/cloud/rescue.tpl create mode 100644 web/resources/views/venix/admin/cloud/templates.tpl delete mode 100644 web/resources/views/venix/admin/hosts/preparation.tpl create mode 100644 web/resources/views/venix/cloud/index.tpl create mode 100644 web/sql/cloud.sql create mode 100644 web/sql/cloud_log.sql create mode 100644 web/tests/CloudFinancialWorkflowTest.php create mode 100644 web/tests/CloudProtocolTest.php create mode 100644 web/tests/CloudSecretsTest.php create mode 100644 web/tests/CloudSessionSecurityTest.php create mode 100644 web/tests/VirtualizationAssetsTest.php create mode 100644 web/tests/VirtualizationConfigTest.php create mode 100644 web/tests/VirtualizationLoginBoundaryTest.php create mode 100644 web/tests/VirtualizationSetupExportTest.php diff --git a/.gitignore b/.gitignore index e11c5cda..1fa01abf 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,7 @@ id_ed25519 *.tar.gz *.tgz *.sql.gz +runtime/ +web/config/config.php +engine/.venv/ +engine/**/__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index 930640da..421653a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,9 +15,12 @@ `web/public/`, not the repository root. - Only the venix theme is retained. Ordinary users must not receive host administration or retired node-management routes. -- This is a pruned, not-yet-integrated development project. Host preparation - pages do not save credentials or connect to Python. Purchasing must remain - disabled until the virtual machine provisioning and billing integration is - implemented and tested. +- PHP owns accounts, wallet purchases, orders, public-key ownership and public + HTTP authorization. The Python engine owns libvirt, host credentials and VM + operations. Keep the engine private and authenticate every internal request. +- Purchases provision one VM from the plan snapshot. This release does not + implement expiry or renewal. Never retry an ambiguous destructive operation + or refund it without confirmed cleanup; reconcile its operation identifier. +- Users share the original VM-panel styling; administrator pages retain venix. - See `docs/PRUNING_REPORT.md` for retained/removed feature boundaries and `docs/INTEGRATION_PLAN.md` for the planned Python engine integration. diff --git a/README.md b/README.md index 5de5fe21..d55aafbb 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,37 @@ -# Virt Cloud 集成开发副本 +# Virt Cloud -当前阶段:已按确认范围清理 PHP 旧业务,尚未实现 PHP 与 libvirt 服务的对接。 +PHP 8.5 网站与私有 Python/libvirt 引擎集成的虚拟机销售面板。使用 `venix` 分支;`main` 的原 virsh-panel 不受影响。 -## 仓库与分支 +## 本版功能 -- 仓库:`https://g.luoli.live/root/virt.git`。 -- 新项目使用 `venix` 分支;后续修改、提交和推送均在此分支进行。 -- `main` 保留现有 virsh-panel,本分支独立存放新项目,尚未包含 Python 引擎。 -- 拉取新项目:`git clone --branch venix --single-branch https://g.luoli.live/root/virt.git virt-cloud`。 +- PHP 统一注册、邮箱登录、账户、充值、支付、SMTP、工单;注册后无需创建审核。 +- 用户购买套餐开通 VM,余额扣款、库存扣减、确认创建失败退款;不包含到期、续费和周期扣费。 +- 套餐绑定宿主机,提供 CPU、内存、磁盘、网络带宽规格,用户不能随意修改套餐资源。 +- 管理员管理多宿主机、云镜像和独立救援 ISO;用户选择已有模板及自己的 SSH 公钥。 +- 用户仅操作自己的 VM:控制台、开关机、软/硬重启、重装、救援、删除、初始 root 密码查看/复制。 +- CPU、内存、磁盘 I/O、网络带宽图表;后台持续采集,写入日志库,最长保留 30 天。 +- 全部用户页及登录页使用原虚拟机面板风格;管理员后台保留 venix 样式。 +- 宿主机凭据及任务密码等敏感数据加密保存;内部请求签名,控制台使用短时一次性凭据。 -## 已完成 +## 目录与部署 -- `web/` 来自 `/Users/admin/Documents/www/html` 的工作目录源码。 -- PHP 来源分支:`php8.5`;来源提交:`f2055f0fca86d84e6b525e54df86c6c685c7eff7`。 -- 虚拟化/UI 参考项目:`/Users/admin/Documents/www/virsh-panel`,参考提交:`626055a42274a43737d636a622661be9223f5ae7`。 -- 原来的两个项目没有修改;副本不继承原 PHP 仓库的 `.git`。 -- 未复制实际 `.env`、`config/.config.php`、监控脚本实际环境文件、依赖目录和运行缓存/日志。保留配置示例、源码、模板、SQL 和静态资源。 -- 未启动网站,未连接真实数据库或宿主机。 -- 仅保留 venix 主题;用户侧节点列表已删除,管理员宿主机页面暂为准备页。 -- 账户表去除代理、流量和账户/等级到期字段;密码改为 bcrypt,保留邮箱账户安全功能。 -- 商城改为 CPU、内存、带宽、硬盘套餐;接入引擎前购买返回 409,不扣余额。 -- 清理前源码已完整备份,删除的主题和检测器也保留了可恢复副本。 +```text +virt-cloud/ + web/ PHP 网站、页面、SQL、测试 + engine/ 私有 FastAPI/libvirt 引擎及测试 + deploy/ 引擎与开通 worker 的 systemd 配置 + runtime/ 私有配置、密钥、引擎数据(安装生成,不入 Git) + docs/ 架构、部署、原清理记录 +``` -## 当前不要部署 +网站文档根目录必须是 `web/public`。引擎仅监听 `127.0.0.1:8000`;不能把整个网站反代到引擎,只有 `/engine-console` 的 WebSocket 转发给引擎。 -这是一份已裁剪、待集成的开发副本,还不是可部署的虚拟机销售面板。 +全新安装见 [部署说明](docs/DEPLOYMENT.md),职责边界见 [集成架构](docs/INTEGRATION_PLAN.md)。配置使用 `web/config/config.php`,兼容旧文件名 `.config.php`;两者存在时前者优先。本版不导入原 Python 面板数据,也不提供在线更新按钮。 -- `web/crontab` 是禁用的任务示例;不要在测试副本中启用真实支付扫描或备份邮件。 -- `web/sql/ss.sql` 是清理后的 PHP 全新账户/销售基础结构,不包含虚拟化引擎和 VM 表;不要在生产数据库中直接执行。 -- 旧节点、订阅、AI、Apple 等路由与实现已删除。 -- 网页首次初始化、引擎集成、统一 CSRF、SMTP 证书校验等仍需继续完成。 +## 验证范围 -## 建议方向 +已进行隔离 PHP 8.5 语法、模板、协议、SQLite 订单状态机和 Python 引擎测试。没有使用真实 MariaDB、SSH/KVM、付款或邮件通道完成生产联调。首次部署请先在测试宿主机验收,再开放销售。 -保留 virsh-panel 的 HTML/CSS/交互布局,PHP 提供同源兼容 API 并负责账户与销售业务;Python 保留 libvirt、宿主机凭据、虚拟机任务、指标和 VNC 转发。 +超时后状态不明的任务保持 `uncertain`,不会直接退款或再次毁盘/创建。管理员需核对宿主机与任务状态,不能靠重复购买处理。这不是自动故障迁移、资源超售防护或高可用平台。 -本轮具体改动与验证见 [清理报告](docs/PRUNING_REPORT.md),后续架构见 [集成方案](docs/INTEGRATION_PLAN.md)。 +原清理边界见 [清理报告](docs/PRUNING_REPORT.md)。原 `/html` 与 `/virsh-panel` 项目未在本轮修改。 diff --git a/deploy/virt-cloud-engine.service b/deploy/virt-cloud-engine.service new file mode 100644 index 00000000..84e0b5ad --- /dev/null +++ b/deploy/virt-cloud-engine.service @@ -0,0 +1,25 @@ +[Unit] +Description=Virt Cloud private libvirt engine +After=network-online.target +Wants=network-online.target + +[Service] +Type=exec +User=root +Group=root +WorkingDirectory=/home/virt-cloud/engine +Environment=CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json +Environment=PYTHONDONTWRITEBYTECODE=1 +ExecStart=/home/virt-cloud/engine/.venv/bin/python -m uvicorn virsh_panel.internal:create_engine --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1 --no-access-log +Restart=on-failure +RestartSec=5 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=false +ReadWritePaths=/home/virt-cloud/runtime +LimitCORE=0 + +[Install] +WantedBy=multi-user.target diff --git a/deploy/virt-cloud-worker.service b/deploy/virt-cloud-worker.service new file mode 100644 index 00000000..9838e26d --- /dev/null +++ b/deploy/virt-cloud-worker.service @@ -0,0 +1,25 @@ +[Unit] +Description=Virt Cloud purchased VM provisioning worker +After=network-online.target virt-cloud-engine.service +Wants=network-online.target + +[Service] +Type=simple +# AlmaLinux PHP-FPM normally runs as apache; use the same user as your PHP pool. +User=apache +Group=apache +WorkingDirectory=/home/virt-cloud/web +ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudWorker +Restart=on-failure +RestartSec=5 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=false +ProtectSystem=strict +ReadWritePaths=-/home/virt-cloud/runtime/php +ReadWritePaths=-/home/virt-cloud/web/storage +TimeoutStopSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 00000000..cd58bc82 --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,150 @@ +# 全新安装与启动 + +没有安装器,不迁移旧 virsh-panel 数据。示例默认 AlmaLinux 面板服务器、项目 `/home/virt-cloud`、PHP-FPM 用户 `apache`;调整实际 PHP 路径、FPM 用户及 service 路径。宿主机是另外的 SSH/libvirt 服务器。 + +## 1. 自行安装依赖 + +- PHP 8.5 CLI/FPM:PDO MySQL、sodium、mbstring、curl、XML/DOM、OpenSSL、session 等扩展,Composer 2。 +- MariaDB/MySQL:业务库、日志库,初始化账号需要建表权限。 +- Redis 或兼容的 Valkey:沿用 venix 会话、验证码与限流。 +- Python 3.12 或更新的项目支持版本、venv/pip、libvirt 客户端及开发头文件、C 编译工具、pkg-config、OpenSSH 客户端。 +- Nginx/Apache、HTTPS、PHP-FPM,网站配置由你自行管理。 + +`libvirt-python` 是面板依赖,不代表面板服务器需要运行 KVM 宿主服务;远端宿主另需现有 KVM/QEMU、libvirt、网桥、UEFI 固件和存储目录。 + +AlmaLinux 编译 Python libvirt 绑定常用系统依赖:`dnf install gcc pkgconf-pkg-config python3-devel libvirt-devel openssh-clients`。Python 可执行文件与开发头文件应使用相同版本。 + +## 2. 拉取与安装程序依赖 + +```bash +git clone --branch venix --single-branch https://g.luoli.live/root/virt.git /home/virt-cloud +cd /home/virt-cloud/web +composer install --no-dev --prefer-dist --optimize-autoloader +cd /home/virt-cloud +python3 -m venv engine/.venv +engine/.venv/bin/python -m pip install -r engine/requirements.txt +engine/.venv/bin/python -c 'import libvirt; print(libvirt.getVersion())' +``` + +已拉取则从安装依赖开始,不要覆盖目录 clone。Python 依赖编译失败先核对系统 `libvirt-devel`、Python 开发头文件与 Python 版本。 + +## 3. 配置与全新数据库 + +```bash +cd /home/virt-cloud/web +cp config/.config.php.example config/config.php +``` + +编辑 `config/config.php`: + +- `db_host/db_port/db_database/db_username/db_password`:业务库。 +- `enable_log` 设置为字符串 `'true'`;`log_db_host/log_db_port/log_db_database/log_db_user/log_db_password`:日志库。空日志库地址沿用本机默认,远程数据库请填写明确地址。 +- `db_prefix` 留空,网站域名、HTTPS Cookie、Redis/Valkey、账户安全、SMTP 按 venix 设置。 +- `cloud_*` 默认路径适配 `/home/virt-cloud`,私有密钥自动生成;宿主机凭据稍后在页面设置。 +- `cloud_introspection_url` 必须指向 PHP 网站,不是引擎 8000。默认 `http://127.0.0.1/api/internal/cloud/session-introspection`;多虚拟主机可设置 `cloud_introspection_host` 为网站域名,或改为正确的本机 HTTPS URL。 + +在**两个全新空数据库**分别导入,替换命令中的地址、端口、账号、库名;`-p` 提示密码,不把密码写入历史: + +```bash +mariadb -h DB_HOST -P DB_PORT -u DB_USER -p BUSINESS_DB < /home/virt-cloud/web/sql/ss.sql +mariadb -h LOG_DB_HOST -P LOG_DB_PORT -u LOG_DB_USER -p LOG_DB < /home/virt-cloud/web/sql/user_log.sql +cd /home/virt-cloud/web +php xcat cloudInit +php xcat createAdmin +``` + +`cloudInit` 新建云业务/指标表、生成独立签名和加密密钥及 `runtime/engine.json`,不连接宿主机。按 CLI 提示创建管理员,邮箱应真实可用;核对 `super_admin` UID 包含有宿主机管理权限的管理员。 + +数据库或内省 URL 修改后重新导出并重启引擎(保留现有密钥): + +```bash +cd /home/virt-cloud/web +php xcat cloudExportConfig +``` + +**不要删除** `runtime/php/payload.key`、`engine.hmac` 或 `runtime/engine/master.key`。备份数据库时同步安全备份密钥,否则加密记录无法使用。 + +## 4. 权限 + +`cloudInit` 成功后以 root 执行,FPM 用户不是 apache 时替换。PHP 不需要读取引擎私钥数据: + +```bash +chown root:apache /home/virt-cloud/runtime +chmod 0750 /home/virt-cloud/runtime +chown -R apache:apache /home/virt-cloud/runtime/php +chmod 0700 /home/virt-cloud/runtime/php +chmod 0600 /home/virt-cloud/runtime/php/engine.hmac /home/virt-cloud/runtime/php/payload.key +chown root:root /home/virt-cloud/runtime/engine.json +chmod 0600 /home/virt-cloud/runtime/engine.json +chown root:apache /home/virt-cloud/web/config/config.php +chmod 0640 /home/virt-cloud/web/config/config.php +mkdir -p /home/virt-cloud/web/storage/framework/smarty/compile /home/virt-cloud/web/storage/framework/smarty/cache +chown -R apache:apache /home/virt-cloud/web/storage +``` + +代码/依赖只需可读,不要整项目 `chmod 777`。在 `/home` 发布需配置父目录遍历权限、SELinux 网站文件标签和所需网络访问策略,不要关闭 SELinux。引擎 root 运行,自行创建私有 `runtime/engine`。 + +## 5. 启动 + +前台调试引擎: + +```bash +cd /home/virt-cloud/engine +PYTHONDONTWRITEBYTECODE=1 CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json .venv/bin/python -m uvicorn virsh_panel.internal:create_engine --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1 +``` + +另一个终端以前台方式运行任务 worker(与 FPM 相同用户): + +```bash +cd /home/virt-cloud/web +sudo -u apache php xcat cloudWorker +``` + +常驻 service: + +```bash +cp /home/virt-cloud/deploy/virt-cloud-engine.service /etc/systemd/system/virt-cloud-engine.service +cp /home/virt-cloud/deploy/virt-cloud-worker.service /etc/systemd/system/virt-cloud-worker.service +systemctl daemon-reload +systemctl enable --now virt-cloud-engine.service virt-cloud-worker.service +systemctl status virt-cloud-engine.service virt-cloud-worker.service --no-pager +journalctl -u virt-cloud-engine -u virt-cloud-worker -n 100 --no-pager +``` + +worker 使用 `/usr/bin/php`,须为 PHP 8.5,否则修改 unit。引擎使用一个 worker。购买排队不执行时先检查 `virt-cloud-worker`。PHP 网站由你现有的 Web/FPM 服务提供。 + +## 6. 网站与控制台 + +文档根目录 `/home/virt-cloud/web/public`,未命中文件的请求交给 Slim 的 `index.php`。**不再使用原面板 `ProxyPass / http://127.0.0.1:8000/`**,普通页面/API 现在由 PHP 提供。 + +仅把 `/engine-console` WebSocket 转发到引擎,保留 Host、Origin、WebSocket 子协议与 Upgrade;发送可信 `X-Forwarded-Proto`。Nginx 示例,map 放在 http 级,location 放在现有 HTTPS server 内: + +```nginx +map $http_upgrade $cloud_connection_upgrade { + default upgrade; + '' close; +} + +location = /engine-console { + proxy_pass http://127.0.0.1:8000/engine-console; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $cloud_connection_upgrade; + proxy_set_header Host $host; + proxy_set_header Origin $http_origin; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 3600s; +} +``` + +不要公开 `/internal/v1/*` 或开放 8000 防火墙。PHP `/api/internal/cloud/session-introspection` 建议在 Web 层限定本机访问,仍有内部签名认证。救援上传需要合适的 FPM/反代超时和请求体上限,最大 ISO 8 GiB,入口只对管理员开放。 + +## 7. 页面配置与验收 + +1. 管理员添加宿主机:现有 SSH/root/私钥口令、核验指纹,设置区域、网桥、目录、地址池/网关/DNS/网卡前缀,测试连接。 +2. 导入云镜像与救援模板;无已有模板不能开通云镜像 VM。当前云镜像下载沿用 AlmaLinux 9/10 官方源校验规则,预存其他系统图标不代表已实现其云模板导入;其他系统可用合适 ISO 安装,云镜像适配后续扩展。 +3. 套餐设置规格、价格、库存、已启用宿主机。本版价格是一次开通金额,不是自动月费。 +4. 测试用户注册/充值/购买,验证任务、VM 控制台、SSH、重装、救援、删除与图表。 +5. 日志库 `engine_vm_metric_samples` 应在所有用户退出后继续新增;首批图表需等待采样间隔。 + +先不要启用旧 `web/crontab`,付款扫描/备份任务按保留业务单独核对。真实 MariaDB/KVM/SMTP/支付未在开发环境联调,先验收测试环境。`uncertain` 状态先核对宿主机,不直接改库退款或重复毁盘任务。 diff --git a/docs/INTEGRATION_PLAN.md b/docs/INTEGRATION_PLAN.md index 15204fdb..8481d49a 100644 --- a/docs/INTEGRATION_PLAN.md +++ b/docs/INTEGRATION_PLAN.md @@ -1,156 +1,64 @@ -# PHP 与虚拟化面板集成方案 +# Virt Cloud 集成架构 -初次审查:2026-09-26;清理状态更新:2026-09-27。本文保留原始架构审查和后续集成建议;已经执行的清理以 [清理报告](PRUNING_REPORT.md) 为准。 +更新:2026-09-27。替代此前“尚未集成”的计划,描述本版实现边界;真实部署仍需测试环境联调。 -## 1. 目标和当前进度 +## 请求链路 -用户确认 PHP 项目为 `/Users/admin/Documents/www/html`,要求继续使用 virsh-panel 现有 UI 与布局,最多微调,不使用旧 PHP 主题替换现有界面。 +```text +浏览器 + ├─ HTTPS 页面/API → PHP:账户、授权、CSRF、套餐、钱包、订单 + │ └─ HMAC 内部 API → Python → SSH/libvirt → 宿主机 + └─ WSS /engine-console ──────────────────→ Python → SSH 隧道 → VM VNC -已经在 `/Users/admin/Documents/www/virt-cloud/web` 的独立副本完成用户确认的旧业务裁剪、账户/套餐结构改造。原 PHP 和 Python 项目没有修改。按最新要求,当前清理阶段只保留 venix,用户侧不再有节点列表,管理员提供未接入的宿主机设置页。Python 引擎与现有虚拟化面板 UI 尚未集成。 +PHP cloudWorker → 持久任务 → Python operation_id → 实例关联/核对/退款 +Python 后台采集 → 日志库 engine_vm_metric_samples → 详情页四项图表 +``` -最终建议在 `virt-cloud` 一个项目目录内管理 PHP 网站、Python 引擎、部署文件和文档;PHP 的 HTTP 文档根目录只指向 `web/public`。内部服务、源码、密钥、数据和部署文件不能成为公开网站目录。 +PHP 是唯一账户入口,所有用户页面使用原虚拟化面板 CSS;后台保留 venix。没有第二套 Python 注册、SMTP、数据库设置或审核流程。 -## 2. 两份代码的实际特点 +## 数据职责 -| 方面 | PHP 项目 | virsh-panel | 集成选择 | -| --- | --- | --- | --- | -| 页面 | Smarty,多套主题,大量旧业务资源 | 独立 HTML/CSS/原生 JS,本地 noVNC | 保留虚拟化面板 UI,不混用旧主题 CSS | -| 框架 | Composer 声明 PHP 8.5、Slim 3、Eloquent 13 | FastAPI、Uvicorn、Pydantic | 暂不进行额外框架升级,先建立清晰服务边界 | -| 账户 | 已有验证码、TOTP、可信设备、会话撤销等,混入代理节点规则 | 独立用户表、邮箱验证、审核、管理员、VM 归属 | PHP 作为唯一账户来源,抽离旧代理规则 | -| 支付 | 易支付、Paytaro、USDT,含回调事务与重复回调处理 | 尚无销售订单或计费领域 | 复用支付网关与钱包基础,新建 VPS 订单和套餐 | -| 虚拟化 | 没有 libvirt 管理能力 | SSH/libvirt、镜像、创建、重装、救援、IP、指标、VNC | 保留 Python 的核心功能及测试 | -| 资源销售 | 原套餐修改流量、等级和订阅期限 | 仅 VM 参数范围校验,无完整销售配额 | 新建套餐、库存、预留、实例期限,不沿用代理套餐 | +| 数据 | 权威写入方 | 存储 | +| --- | --- | --- | +| 用户、钱包、套餐、原财务/工单 | PHP | 原业务库表 | +| 宿主机索引、订单、实例、公钥、会话、任务 | PHP | `cloud_hosts/orders/instances/ssh_keys/sessions/jobs` | +| 宿主机凭据、VM 元数据、镜像、操作进度 | Python | 主库 `engine_records`,敏感记录加密 | +| 引擎签名防重放 | Python | 主库 `engine_request_nonces` | +| 四项性能指标样本 | Python | 日志库 `engine_vm_metric_samples`,保留 30 天 | -PHP 基础入口为 `public/index.php` → `bootstrap.php` → `config/routes.php`。当前 bootstrap 强制读取 `config/.config.php`,不能直接实现用户要求的网页首次初始化;后续必须改造引导流程,不能再要求两套手工配置和两次创建账户。 +多个宿主机使用稳定 `host_id`,不共用一个可切换的全局“当前宿主机”。模板、IP 地址池、网关、DNS、虚拟机网卡前缀、磁盘/ISO/救援目录均按宿主机设置。地址池与网卡前缀分开:供应商地址池可以为 /28,虚拟机网卡可以为 /24,不能因此把售卖范围扩大为 /24。 -PHP `UserController.php` 有 2254 行、`AuthController.php` 有 1265 行、`AdminController.php` 有 793 行。它们不是干净的通用账户模块,需要拆分而不是继续往里面堆虚拟机业务。 +PHP 不直接解密 Python 记录或执行任意 virsh 命令。主库与日志库可同实例或分别配置地址/端口。敏感业务数据加密;部署数据库连接配置仍是权限受限配置文件,不代表配置文件本身加密。 -## 3. UI 保留方式 +## 购买状态机 -保留 `/Users/admin/Documents/www/virsh-panel/static/index.html`、`styles.css`、`app.js`、系统图标和本地 noVNC,移到新网站自身的公开资源位置。保留面板的侧栏、卡片、虚拟机列表、详情、创建、重装、救援和四项指标布局。 +1. 用户选择启用套餐、已有系统来源、公钥/强 root 密码,提交幂等键。 +2. PHP 事务锁定用户钱包与套餐,校验余额、库存、宿主机与实例配额,保存不可由浏览器改写的规格快照,扣款并保存加密任务。 +3. 独立 `cloudWorker` 获取租约,携带唯一 `operation_id` 请求引擎。只有经过签名的开通上下文可以创建 VM,用户不能免费创建。 +4. 成功关联实例和凭据;确认创建失败且无残留时只退款、恢复库存一次。 +5. 超时、引擎中断或残留无法确认时保持待核对,只查询原操作,不重复创建或盲目退款。 -不把旧 Material/Codex/Venix 主题的 CSS、导航或布局加入这些页面;现有面板样式含全局 `body`、通配符等规则,直接混合会互相覆盖。首版在根路径提供现有面板页面,避免无必要地改动绝对资源路径;如果后续挂载到 `/virt`,再明确处理 UI 路径与 API 路径。 +金额通过精确小数与整数最小单位换算处理,不用浮点完成扣款比较。套餐带宽转换成 libvirt 网卡双向 KiB/s 限制。本轮没有续费、月结、到期停机、自动回收或套餐升级。 -面板的 HTTP 请求集中于 `static/app.js` 的 `api()`,因此 PHP 实现兼容的 `/api/v1/...` 接口门面即可保留大部分交互。不要把 4000 多行 JS 全部改写成 Smarty 页面,也不要把现有网站 iframe 嵌到面板或反过来嵌入。 +## 安全与控制台 -新增余额、套餐、订单、续费、工单等功能时,用现有面板的组件和样式补充页面,不引入第二套用户界面。 +- 用户 ID、角色、VM 归属由 PHP 确定,不能相信浏览器身份字段;引擎再次检查归属。 +- 管理员与 `super_admin` 白名单权限分开;跨用户只读不自动获得跨用户写权限。 +- 云 API 写操作校验 CSRF;未登录/无权限返回 JSON,不重定向 HTML。 +- HMAC 覆盖方法、完整路径/查询、请求体摘要、时间戳、nonce、身份。防重放存储是共享的持久数据库/Redis。 +- PHP 签名密钥与任务加密密钥独立生成;任务使用 sodium secretbox 随机 nonce,引擎有独立 master.key。备份时保存密钥,不能删除后期待解密数据。 +- root 公钥和密码可以同时设置,未填密码时生成强密码;root 密码策略独立于网站 bcrypt 的 72 字节限制。 -### 需要保持的接口契约 +VNC 凭据 60 秒有效、单次、绑定用户/VM/会话,通过 WebSocket 子协议传递而非 URL。连接期间持续校验 PHP 会话,退出或停权会阻止继续访问。线上使用 HTTPS/WSS。 -- 会话字段:`authenticated`、`admin`、`approved`、`host_ready` 必须是 JSON 布尔值,不是 `"1"` 字符串;保留 `username`、`csrf_token` 等字段。 -- 列表、模板、VM 详情、指标和任务的响应字段、状态码需要建立契约测试。 -- API 未登录返回 JSON 401,无权限返回 JSON 403;不能沿用 PHP 页面中间件的 302 HTML 登录重定向。 -- 浏览器写操作使用统一 CSRF 校验,覆盖普通用户与管理员。 -- 当前前端先查询数据库状态、初始化状态和会话。整合后统一由 PHP 首次引导管理,避免又进入 Python 的第二套注册流程。 -- `/api/v1` 当前未与 PHP 的旧 `/api` 路由重名,但仍应使用新的限定路由表,不携带旧代理 API。 +## 原虚拟化功能与限制 -## 4. 服务与数据职责 +保留云镜像/ISO 创建、UEFI/ACPI、host-passthrough、virtio 队列随 vCPU、开机自启、首次安装重启停止并弹出 ISO、磁盘删除、重装网络保留、救援挂载/卸载、SSH 隧道 VNC。救援正常关机失败不会自动断电,用户可确认硬重启,主动退出救援前 ISO 保持挂载。 -### PHP:网站和销售控制面 +重装、救援、删除使用持久操作编号,进程中断不盲目重复破坏性步骤。救援 ISO 为管理员授权原始流上传及摘要校验;线上需配置 FPM/反代超时与大小限制。 -负责唯一账户体系、邮箱验证、管理员权限、账户批准/禁用、用户公钥管理、套餐、订单、充值、支付、续费、工单和用户操作授权。管理员宿主机和镜像页面仍保留原 UI,由 PHP API 转交引擎。 +尚未实现宿主容量调度、分布式资源预留、IP/MAC 防伪、套餐磁盘 IOPS、备份、热迁移或 HA。线程中断进入待核对,并非完整步骤恢复;后续应增加运维对账与独立执行器。 -### Python:私有虚拟化引擎 +上线前必须验收真实 MariaDB 并发、两库权限、宿主机固件/网桥/SELinux、cloud-init 与 SSH、浏览器 WSS、会话撤销、失败清理/退款。SMTP 沿用 venix,TLS 证书校验已恢复,自签邮件证书需修复信任链。 -负责宿主机 SSH/libvirt、宿主机密钥、实际 IP 占用、镜像文件、虚拟机生命周期、磁盘、重装/救援状态、指标、控制台转发及底层资源校验。 - -PHP 不直接解密或修改 Python 的 `panel_records`,也不直接执行客户端传来的 SSH/virsh 命令。宿主机私钥与口令不需要发给浏览器或存入 PHP 用户表。 - -### 服务认证和归属隔离 - -- Python 内部 API 增加独立的服务认证与经过验证的租户上下文;不能复用一个 Python 管理员 Cookie 代表所有客户。 -- 用户 ID、角色和 VM 归属由 PHP 服务确定,不能直接相信浏览器提交的 `user_id`、`admin` 或 HTTP 自定义身份头。 -- 使用稳定外部用户 ID 与稳定 VM ID,明确映射到引擎归属;不要通过复制两套用户表或共享用户密码来建立身份。 -- 引擎仍核验每个 VM 操作的归属、角色和状态,不能只靠前端隐藏按钮。 -- 订单开通使用幂等键,重复支付回调、网络超时重试不能重复创建 VM 或重复扣款。 - -可以继续用同一 MariaDB 实例,但 PHP 与 Python 按职责区分表/库和数据库账号。建议有明确的账户、套餐、订单、服务实例、宿主机、VM、IP 预留、任务和审计模型;同一数据只能有一个权威写入方。订单中的期望配置由 PHP 管理,宿主实际运行状态由引擎返回并对账。 - -现有 Python 仍然只有一个宿主机配置。此次集成不会自动成为多宿主机平台,多宿主机需要稳定 `host_id`、调度和资源预留另外开发。 - -## 5. VNC、大文件和耗时任务 - -### VNC - -保留 noVNC 与 Python WSS→SSH→宿主机本地 VNC 链路。PHP 校验用户后向引擎申请短时、单 VM、可撤销的控制台凭据;浏览器通过同源反代直接连接 Python WebSocket。不让普通 PHP-FPM 请求持续搬运控制台二进制流,也不向客户开放宿主机 VNC 端口或暴露内部服务凭据。 - -凭据需要绑定用户、VM、过期时间与会话状态,握手验证,并保留注销/停权后的持续访问检查。不能只把当前 Python console 的 Cookie 校验删掉。 - -### 救援 ISO 上传 - -当前 UI 发送 `application/octet-stream` 原始流,最大 8 GiB,不是 multipart。需要专门的授权和流式上传通道,避免 PHP 全量读进内存、重复暂存文件或长时间占用普通 FPM worker。禁止先完整接收再检查上传权限。 - -### 后台任务 - -创建、重装、救援和镜像下载应返回任务编号,由 UI 查询进度。现有 Python 重装/救援等任务仍运行在 Web 进程中的线程;集成不会自动获得重启恢复。长期要拆独立 worker 与指标采集,持久记录任务步骤、锁、租约、失败状态和宿主实际状态对账,不能对毁盘/删除操作盲目重试。 - -## 6. PHP 代码保留与移除边界 - -### 提取后保留 - -- Composer、Slim 路由、Eloquent 连接和模型基础。 -- 注册登录、验证码、密码找回、TOTP、可信设备、会话撤销、邮箱/IP 限制等可选账户安全能力。 -- 管理员权限、CSRF、SMTP/邮件投递记录;与 Python 现有 UI 统一。 -- `app/Services/Payment/` 中需要使用的支付网关、签名校验、重复回调与钱包充值能力。 -- 工单、公告、必要的访问安全日志和用户操作审计。 -- Redis 暂时保留:认证、验证码限流、可信设备和缓存仍有依赖,不能仅删除节点模块就删除 Redis。 - -### 默认不带入首版虚拟化业务 - -- AI:`config/routes_ai.php`、`app/Services/Ai/`、AI 控制器/模型/路由/定时任务。 -- 代理节点、订阅、客户端配置生成:Node/Link/Conf/EdgeConfig/代理 DNS 分发,以及 `resources/conf/`。 -- 代理流量、在线人数、TCP 与 Gemini 节点监控及相应采集脚本。 -- Apple 账号池、账号检测配套目录、Apple 用户权限与领取日志。 -- 原代理 `Shop`/`Bought` 套餐、流量重置、会员等级过期和代理自动续费规则。 -- 与首版无关的社区、问卷、Telegram/机器人、付费注册等功能。 -- 原多主题页面和 `public/theme/` 大量资源:迁入现有面板 UI 并确认无依赖后退役。 -- 旧 SQL、旧部署 cron 和仅针对退役模块的测试/文档/依赖。 - -以上为初次审查建议,不是最终删除清单。实际按用户反馈保留了商城、支付、工单、问卷、人工限制以及管理员专用 Telegram 工单通知;套餐已改为资源规格但不能购买。保留/删除细节见清理报告。 - -### 不能盲目删除的耦合 - -- `Services/Auth/Redis.php`、`Auth/Cookie.php` 的身份查询还访问 Node,删除节点前先移除这条依赖。 -- `AuthController.php` 注册会分配代理密码、端口、协议、流量和等级,需改成干净账户初始化。 -- `Models/Shop.php::buy()` 修改流量和会员等级,不会创建虚拟机;不能只改文字当作 VPS 套餐。 -- `UserFeatureRestrictionService`、`UserRestrictionEnforcementService` 按代理使用量与旧套餐判断限制,可能把正常 VPS 客户误封。 -- `View.php` 和用户首页依赖旧套餐/AI 服务,删除模块后需要解除共用渲染依赖。 -- `UserDataDeletionService` 跨主库/日志库批量清理旧业务。VPS 用户删除必须先处理仍在运行的实例、磁盘、订单与归属,不能只删账户。 -- `Job.php`、`AccountLifecycleService`、`TransientDataCleanupService` 不是通用云服务任务,不直接保留原行为。 -- 原日志库还有邮件/安全统计用途,不能因删除代理日志就移除所有日志连接。 - -## 7. 集成前必须修复的安全和数据问题 - -1. 密码:`app/Utils/Hash.php` 使用 MD5 或单次 SHA-256 + 全局盐。新账户改用 `password_hash()` / `password_verify()`,使用足够宽的哈希列;不沿用旧 `pass VARCHAR(64)`。全新安装不必兼容旧散列。 -2. 邮件 TLS:`Services/Mail/Smtp.php` 的部分 SSL 路径关闭证书/主机名验证,需要恢复验证,不能把关闭验证作为解决证书错误的默认方式。 -3. 权限:统一 `is_admin` 与配置中的 `super_admin` UID 白名单;所有 API 写操作增加一致 CSRF 与资源归属检查。 -4. 找回密码:一次性 token 事务消费、过期限制、修改后撤销旧会话,删除旧订阅清理副作用。 -5. 金额:新销售逻辑采用整数最小货币单位或精确 Decimal 运算,保留币种和价格快照,避免 PHP float 处理扣款。 -6. 配额:支付成功不等于可以无限开机。增加用户/套餐资源限制、宿主容量预留、IP/MAC 防伪与带宽/磁盘 I/O 约束。 -7. 更新:原在线更新器固定指向旧 virsh-panel 仓库。新复合项目必须设计自己的版本与更新范围;不能直接搬入后让其覆盖整个 PHP 新项目。 - -相关官方资料:[PHP 密码哈希](https://www.php.net/manual/en/function.password-hash.php)、[PHP 密码验证](https://www.php.net/manual/en/function.password-verify.php)、[Guzzle JSON/TLS 请求选项](https://docs.guzzlephp.org/en/stable/request-options.html)、[FastAPI WebSocket 认证与依赖](https://fastapi.tiangolo.com/advanced/websockets/)。 - -## 8. 建议实施顺序与验收 - -### 第一阶段:无销售的最小集成 - -建立新的限定路由表与干净账户模型;统一首次网页初始化、邮箱验证/审核、管理员权限、CSRF;引入现有面板 UI;完成私有引擎认证、用户归属和控制台凭据。先验证登录、自己的公钥和 VM、创建、开关机、重装、救援、指标、管理员配置均与原面板相当。 - -不要启用副本里的旧 `crontab`,不要直接导入 `sql/ss.sql`。后续新数据库不需要兼容原测试数据,但仍需正式初始化/版本化迁移和备份方案。 - -### 第二阶段:按依赖清理 - -在保留功能的测试覆盖下,按“路由和 cron → 共享调用拆分 → 控制器/服务 → 模型/SQL → 模板和资源 → Composer 依赖”顺序删除旧模块。不通过隐藏菜单代替关闭旧 API。 - -保留支付回调签名校验、重复回调与并发入账测试;新增跨用户 VM/公钥隔离、非管理员宿主机操作拒绝、CSRF、错误响应格式、noVNC 和 ISO 流式上传测试。 - -### 第三阶段:销售能力 - -新增 VPS 套餐、区域、价格、订单、实例期限和续费,再连接已审查的支付网关;建立支付入账与实例开通的幂等状态机。开通失败要能重试/退款,不直接用旧 `Shop::buy()`。 - -### 第四阶段:平台可靠性 - -稳定宿主机/VM ID、多宿主机调度与库存、独立 worker/采集进程、备份恢复、审计与报警。再考虑在线扩容、迁移和 HA,不把 PHP UI 集成等同于这些能力已经存在。 - -清理后的代码已进行隔离 PHP 8.5 语法和边界测试。尚未进行真实数据库初始化、邮件/TG/支付通道联调、宿主机操作或生产部署;这些需要在后续集成验收中完成。原始安全审查中密码及找回流程已改造,SMTP TLS 和统一普通用户 CSRF 等仍需后续处理。 +全新安装见 [DEPLOYMENT.md](DEPLOYMENT.md),历史清理见 [PRUNING_REPORT.md](PRUNING_REPORT.md)。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md new file mode 100644 index 00000000..37e7d1f0 --- /dev/null +++ b/docs/VALIDATION.md @@ -0,0 +1,26 @@ +# 本版验证记录 + +2026-09-27,集成代码的隔离验证,不代表生产验收。 + +- Python 3.12:445 passed、10 skipped、39 subtests passed。覆盖原虚拟化逻辑及私有 API、签名/重放、多宿主机归属、持久幂等、一次性 VNC、退出后断权、带宽 XML、救援上传摘要。 +- 隔离 PHP 8.5.10:源码语法、70 个 Smarty 模板、178 个路由目标、精确金额/HMAC、SQLite 购买开通/退款/超时核对/配额/租户隔离、Cookie/Redis 会话撤销及内省、统一用户资源和 52 个 noVNC 模块检查通过。 +- Chrome 使用模拟 API 检查套餐购买、VM 详情/指标/凭据、公钥、重装/救援、后台宿主机/镜像操作与 CSRF;用户账户及登录等页面进行桌面/手机布局检查。不连接真实数据库或宿主机。 +- PHP 隔离环境不提供 sodium:`CloudSecretsTest` 明确跳过,原 Paytaro/易支付密钥加密测试因同一缺失无法运行;财务/会话测试的加密存储仅用明确标注的测试替身,不作为实际加密验证。生产必须安装 sodium,没有弱加密回退。 +- Python 的跳过项需要真实 libvirt/网络环境。没有验证真实 MariaDB 并发、AlmaLinux systemd、宿主机 VM 操作、SMTP、支付和大文件上传。 + +## 在具备依赖的环境复测 + +不要使用生产数据库/宿主机运行额外真实集成测试;以下默认单元/隔离测试: + +```bash +cd /home/virt-cloud/web +for test_file in tests/*Test.php; do php "$test_file" || exit $?; done + +cd /home/virt-cloud/engine +.venv/bin/python -m pip install -r requirements-dev.txt +PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest -q -p no:cacheprovider +``` + +PHP 测试需 Composer 开发可用依赖和测试所用 PDO SQLite。测试中的模拟凭据、地址与密钥不是部署配置。 + +上线前按 [部署说明](DEPLOYMENT.md) 完成测试用户的实际购买、首次 SSH 登录、重装、救援、VNC 撤销、故障清理退款与无人登录时持续采样。共享公网网桥的 IP/MAC 防欺骗及宿主容量调度尚未提供,不能只凭单元测试开放不受信任客户的资源销售。 diff --git a/engine/.gitignore b/engine/.gitignore new file mode 100644 index 00000000..7d95973a --- /dev/null +++ b/engine/.gitignore @@ -0,0 +1,5 @@ +.venv/ +data/ +__pycache__/ +*.py[cod] +.pytest_cache/ diff --git a/engine/requirements-dev.txt b/engine/requirements-dev.txt new file mode 100644 index 00000000..4ef1f321 --- /dev/null +++ b/engine/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +httpx>=0.27,<1 +pytest>=8,<10 diff --git a/engine/requirements.txt b/engine/requirements.txt new file mode 100644 index 00000000..59e462aa --- /dev/null +++ b/engine/requirements.txt @@ -0,0 +1,8 @@ +fastapi>=0.115,<1 +uvicorn[standard]>=0.34,<1 +pydantic>=2,<3 +pycdlib>=1.14,<2 +passlib>=1.7.4,<2 +PyMySQL>=1.1,<2 +cryptography>=44,<49 +libvirt-python>=10,<13; sys_platform == "linux" diff --git a/engine/static/almalinux-icon.svg b/engine/static/almalinux-icon.svg new file mode 100644 index 00000000..2d3719fb --- /dev/null +++ b/engine/static/almalinux-icon.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + diff --git a/engine/static/app.js b/engine/static/app.js new file mode 100644 index 00000000..f1bf2ac6 --- /dev/null +++ b/engine/static/app.js @@ -0,0 +1,4090 @@ +const byId = (id) => document.getElementById(id); +const REINSTALL_JOB_STORAGE_PREFIX = "virsh-panel:reinstall-job:"; +const RESCUE_UPLOAD_MAX_BYTES = 8 * 1024 * 1024 * 1024; +const RESCUE_IMPORT_STORAGE_PREFIX = "virsh-panel:rescue-import:"; +const RESCUE_JOB_STORAGE_PREFIX = "virsh-panel:rescue-job:"; +const UPDATE_REPOSITORY_URL = "https://g.luoli.live/root/virt.git"; +const UPDATE_BRANCH = "main"; + +const state = { + csrfToken: "", + sessionEpoch: 0, + username: "", + admin: false, + approved: false, + hostReady: false, + vms: [], + selectedVmId: null, + credentialVmId: null, + credentialPassword: "", + credentialVisible: false, + credentialBusy: false, + credentialRequestToken: 0, + credentialHideTimer: null, + vmActionInFlight: null, + metricsRange: "24h", + metricsPollTimer: null, + metricsRequest: null, + metricsPayload: null, + metricsResizeTimer: null, + resources: null, + sshKeys: [], + sshKeysLoad: null, + sshKeysReturnView: null, + templateLoad: null, + templates: [], + templateImportJobId: null, + rescueTemplates: [], + rescueTarget: null, + rescueActive: false, + rescueStaged: false, + rescuePowerState: "unknown", + rescueCanExit: false, + rescueJobId: null, + rescuePollToken: 0, + rescueInProgress: false, + rescueUploading: false, + rescueImportJobId: null, + rescueUploadPollToken: 0, + loadingVMs: false, + pollTimer: null, + activeModal: null, + lastFocus: null, + deleteTarget: null, + confirmTarget: null, + reinstallTarget: null, + reinstallJobId: null, + reinstallInProgress: false, + reinstallExpectGeneratedPassword: false, + reinstallPasswordPendingAck: false, + reinstallPollToken: 0, + rfb: null, + consoleToken: 0, + hostConfig: null, + scannedHost: null, + uploadedPrivateKey: "", + updateSettings: null, + updateCheck: null, + updateJobId: null, + updateLastShownJobId: null, + updatePollToken: 0, + updateReturnView: null, +}; + +function text(id, value) { + byId(id).textContent = value; +} + +function clearVmCredential() { + state.credentialRequestToken += 1; + if (state.credentialHideTimer) window.clearTimeout(state.credentialHideTimer); + state.credentialHideTimer = null; + state.credentialVmId = null; + state.credentialPassword = ""; + state.credentialVisible = false; + state.credentialBusy = false; + text("vm-detail-root-password", "未记录"); + const reveal = byId("vm-detail-password-reveal"); + reveal.hidden = true; + reveal.setAttribute("aria-pressed", "false"); + reveal.setAttribute("aria-label", "查看初始 root 密码"); + reveal.title = "查看初始 root 密码"; + byId("vm-detail-password-copy").hidden = true; +} + +async function copyText(value) { + if (navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(value); + return; + } catch { /* Fall back for browsers without clipboard permission. */ } + } + const field = document.createElement("textarea"); + field.value = value; + field.setAttribute("readonly", ""); + field.style.position = "fixed"; + field.style.opacity = "0"; + document.body.append(field); + field.select(); + let copied = false; + try { copied = document.execCommand("copy"); } finally { + field.value = ""; + field.remove(); + } + if (!copied) throw new Error("浏览器无法复制,请手动选择文本。"); +} + +function showError(id, message) { + const element = byId(id); + element.textContent = message; + element.hidden = !message; +} + +function resourceWarnings(payload) { + if (Array.isArray(payload?.warnings)) return payload.warnings.filter((item) => typeof item === "string" && item.trim()); + return typeof payload?.resource_warning === "string" && payload.resource_warning.trim() ? [payload.resource_warning] : []; +} + +function showResourceWarning(message) { + const element = byId("resource-warning"); + element.textContent = message; + element.hidden = !message; +} + +function toast(message, kind = "info") { + const item = document.createElement("div"); + item.className = `toast ${kind}`; + item.textContent = message; + byId("toast-region").append(item); + window.setTimeout(() => item.remove(), 5000); +} + +function errorMessage(payload, fallback) { + if (typeof payload?.error === "string") return payload.error; + if (typeof payload?.message === "string") return payload.message; + if (typeof payload?.detail === "string") return payload.detail; + return fallback; +} + +async function api(path, options = {}) { + const method = options.method || "GET"; + const headers = { Accept: "application/json" }; + if (options.rawBody !== undefined) headers["Content-Type"] = options.contentType || "application/octet-stream"; + else if (options.body !== undefined) headers["Content-Type"] = "application/json"; + if (((method !== "GET" && method !== "HEAD" && options.csrf !== false) || options.csrf === true) && state.csrfToken) { + headers["X-CSRF-Token"] = state.csrfToken; + } + + let response; + try { + response = await fetch(path, { + method, + headers, + credentials: "same-origin", + cache: "no-store", + signal: options.signal, + body: options.rawBody !== undefined ? options.rawBody + : options.body === undefined ? undefined : JSON.stringify(options.body), + }); + } catch (error) { + if (options.signal?.aborted) throw error; + throw new Error("无法连接面板服务,请检查网络或稍后重试。"); + } + + let payload = null; + if (response.status !== 204) { + try { payload = await response.json(); } catch { /* A failed HTTP response may not be JSON. */ } + } + if (response.status === 401 && path !== "/api/v1/login" && path !== "/api/v1/session" && !path.startsWith("/api/v1/register") && !path.startsWith("/api/v1/setup/") && !path.startsWith("/api/v1/database/")) { + showLogin(); + throw new Error("登录已过期,请重新登录。"); + } + if (response.status === 423 && payload?.error_code === "key_locked" && path !== "/api/v1/host/unlock") { + if (state.admin) { + showUnlockView({ ...state.hostConfig, configured: true, key_locked: true }); + throw new Error("宿主机私钥已锁定,请输入私钥口令解锁。"); + } + showAccessWait("host"); + throw new Error("宿主机暂不可用,请联系管理员解锁私钥。"); + } + if (!state.admin && response.status === 409 && /宿主机/.test(errorMessage(payload, "")) && (path.startsWith("/api/v1/vms") || path === "/api/v1/resources")) { + showAccessWait("host"); + throw new Error("宿主机尚未就绪,请等待管理员完成配置。"); + } + if (!state.admin && response.status === 403 && /审核/.test(errorMessage(payload, ""))) { + showAccessWait("approval"); + throw new Error("账号正在等待管理员审核。"); + } + if (!response.ok) { + const error = new Error(errorMessage(payload, `请求失败(HTTP ${response.status})`)); + error.status = response.status; + throw error; + } + return payload; +} + +function stopPolling() { + if (state.pollTimer) window.clearInterval(state.pollTimer); + state.pollTimer = null; +} + +function clearAdminContent() { + for (const id of ["smtp-host", "smtp-username", "smtp-password", "smtp-from-address", "host-address", "host-region", "host-storage-pool", "host-iso-pool", "host-network", "host-public-pool-cidr", "host-public-gateway", "host-public-vm-prefix", "host-public-dns", "host-public-reserved"]) byId(id).value = ""; + refreshPublicPoolPreview(); + byId("smtp-port").value = 465; + byId("smtp-tls-mode").value = "ssl"; + byId("smtp-status").hidden = true; + byId("pending-users-list").replaceChildren(); + showError("smtp-error", ""); + showError("pending-users-error", ""); + text("host-fingerprint", ""); + text("current-username", "用户"); + byId("rescue-template-upload-form").reset(); + byId("rescue-template-list").replaceChildren(); + showError("rescue-template-upload-error", ""); + showError("rescue-template-list-error", ""); +} + +function showLogin() { + stopPolling(); + stopVmMetrics(); + closeModal(); + resetCreatePage(); + resetReinstallPage(); + clearVmCredential(); + state.updatePollToken += 1; + state.updateJobId = null; + state.updateLastShownJobId = null; + state.updateCheck = null; + state.updateSettings = null; + state.updateReturnView = null; + state.sessionEpoch += 1; + state.csrfToken = ""; + state.admin = false; + state.approved = false; + state.hostReady = false; + state.vms = []; + state.sshKeys = []; + state.sshKeysLoad = null; + state.sshKeysReturnView = null; + state.resources = null; + state.hostConfig = null; + state.templateLoad = null; + state.templates = []; + state.templateImportJobId = null; + state.rescueTemplates = []; + state.rescueTarget = null; + state.rescueActive = false; + state.rescueStaged = false; + state.rescuePowerState = "unknown"; + state.rescueCanExit = false; + state.rescueJobId = null; + state.rescuePollToken += 1; + state.rescueInProgress = false; + state.rescueUploading = false; + state.rescueImportJobId = null; + state.rescueUploadPollToken += 1; + state.selectedVmId = null; + clearAdminContent(); + renderVMs(); + clearVmMetrics("登录后加载监控数据。"); + fillSelect("vm-network", [], "network"); + fillSelect("vm-iso", [], "iso"); + fillTemplateViews([]); + fillSshKeyCards([]); + byId("ssh-keys-list").replaceChildren(); + byId("ssh-key-form").reset(); + showError("ssh-key-form-error", ""); + showError("ssh-keys-list-error", ""); + text("vm-detail-name", "虚拟机"); + text("vm-detail-header-ip", "未获取"); + text("vm-detail-header-region", "未设置"); + text("vm-detail-header-created-at", "未记录"); + clearHostPrivateKey(); + byId("unlock-passphrase").value = ""; + byId("update-access-token").value = ""; + byId("smtp-password").value = ""; + byId("admin-menu").open = false; + byId("login-success").hidden = true; + byId("register-code-status").hidden = true; + byId("boot-screen").hidden = true; + byId("database-view").hidden = true; + byId("setup-view").hidden = true; + byId("access-wait-view").hidden = true; + byId("host-view").hidden = true; + byId("unlock-view").hidden = true; + byId("dashboard-view").hidden = true; + byId("login-view").hidden = false; + byId("register-card").hidden = true; + byId("login-card").hidden = false; + byId("register-password").value = ""; + byId("register-password-confirm").value = ""; + byId("register-code").value = ""; +} + +function showRegister() { + showError("register-error", ""); + showError("login-error", ""); + byId("login-card").hidden = true; + byId("register-card").hidden = false; + byId("register-username").focus(); +} + +function showAccessWait(kind) { + stopPolling(); + stopVmMetrics(); + closeModal(); + clearVmCredential(); + const approval = kind === "approval"; + text("wait-current-user", state.username || "用户"); + text("wait-eyebrow", approval ? "ACCOUNT APPROVAL" : "HOST SETUP"); + text("wait-title", approval ? "等待管理员审核" : "等待管理员配置宿主机"); + text("wait-description", approval + ? "邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机;现在可以先导入自己的公钥。" + : "管理员尚未完成宿主机配置,暂时无法创建或管理虚拟机。现在可以先导入自己的公钥,稍后点击“刷新状态”。"); + byId("boot-screen").hidden = true; + for (const id of ["database-view", "setup-view", "login-view", "host-view", "unlock-view", "dashboard-view"]) byId(id).hidden = true; + byId("access-wait-view").hidden = false; +} + +function showDatabaseView() { + stopPolling(); + stopVmMetrics(); + closeModal(); + clearVmCredential(); + byId("boot-screen").hidden = true; + byId("setup-view").hidden = true; + byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; + byId("host-view").hidden = true; + byId("unlock-view").hidden = true; + byId("dashboard-view").hidden = true; + byId("database-view").hidden = false; +} + +function showSetup() { + stopPolling(); + stopVmMetrics(); + closeModal(); + clearVmCredential(); + byId("unlock-passphrase").value = ""; + byId("boot-screen").hidden = true; + byId("database-view").hidden = true; + byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; + byId("host-view").hidden = true; + byId("unlock-view").hidden = true; + byId("dashboard-view").hidden = true; + byId("setup-view").hidden = false; +} + +function clearHostPrivateKey() { + state.uploadedPrivateKey = ""; + byId("host-private-key").value = ""; + byId("host-private-key-file").value = ""; + byId("host-private-key-passphrase").value = ""; + text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。"); +} + +function showUnlockView(hostConfig) { + stopPolling(); + stopVmMetrics(); + closeModal(); + clearVmCredential(); + state.hostConfig = hostConfig; + clearHostPrivateKey(); + byId("unlock-passphrase").value = ""; + showError("unlock-error", ""); + text("unlock-current-user", state.username || "管理员"); + text("unlock-host-label", hostConfig?.host ? `${hostConfig.host}:${hostConfig.port || 22}` : "当前宿主机"); + byId("boot-screen").hidden = true; + byId("database-view").hidden = true; + byId("setup-view").hidden = true; + byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; + byId("host-view").hidden = true; + byId("dashboard-view").hidden = true; + byId("unlock-view").hidden = false; +} + +function resetFingerprint() { + state.scannedHost = null; + byId("host-fingerprint-result").hidden = true; + byId("host-confirm-row").hidden = true; + byId("host-fingerprint-confirm").checked = false; + text("host-test-status", "主机地址或端口已变更,请重新扫描并核对指纹。"); + byId("host-test-status").classList.remove("success", "warning"); +} + +function markHostTestStale() { + if (byId("host-test-status").classList.contains("success") || byId("host-test-status").classList.contains("warning")) { + text("host-test-status", "配置已变更;保存时会重新测试连接。"); + byId("host-test-status").classList.remove("success", "warning"); + } +} + +function showHostView(hostConfig = { configured: false }) { + if (!state.admin) return; + byId("admin-menu").open = false; + stopPolling(); + stopVmMetrics(); + closeModal(); + clearVmCredential(); + state.hostConfig = hostConfig; + clearHostPrivateKey(); + byId("unlock-passphrase").value = ""; + state.scannedHost = null; + byId("host-fingerprint-result").hidden = true; + byId("host-confirm-row").hidden = true; + byId("host-fingerprint-confirm").checked = false; + showError("host-error", ""); + text("host-current-user", state.username || "管理员"); + const configured = Boolean(hostConfig.configured); + text("host-step-label", configured ? "HOST SETTINGS" : "管理员操作"); + text("host-page-title", configured ? "宿主机设置" : "连接 libvirt 宿主机"); + text("host-save-button", configured ? "保存修改" : "保存并进入面板"); + byId("host-back-button").hidden = !configured; + byId("host-address").value = configured ? (hostConfig.host || "") : ""; + byId("host-port").value = configured ? (hostConfig.port || 22) : 22; + byId("host-region").value = configured ? (hostConfig.region || "") : ""; + byId("host-storage-pool").value = configured ? (hostConfig.storage_pool || "default") : "default"; + byId("host-iso-pool").value = configured ? (hostConfig.iso_pool || "iso") : "iso"; + byId("host-rescue-iso-pool").value = configured ? (hostConfig.rescue_iso_pool || "") : ""; + byId("host-network").value = configured ? (hostConfig.default_network || "default") : "default"; + byId("host-public-pool-cidr").value = configured ? (hostConfig.public_pool_cidr || "") : ""; + refreshPublicPoolPreview(); + byId("host-public-gateway").value = configured ? (hostConfig.public_gateway || "") : ""; + byId("host-public-vm-prefix").value = configured && Number.isInteger(hostConfig.public_vm_prefix) ? String(hostConfig.public_vm_prefix) : ""; + byId("host-public-dns").value = configured && Array.isArray(hostConfig.public_dns_servers) ? hostConfig.public_dns_servers.join(", ") : ""; + byId("host-public-reserved").value = configured && Array.isArray(hostConfig.public_reserved_ips) ? hostConfig.public_reserved_ips.join("\n") : ""; + text("host-key-required-mark", configured ? "" : "*"); + text("host-key-hint", configured + ? "留空则继续使用已保存的私钥;填写或选择文件会替换它。已保存私钥不会回显。" + : "仅通过 HTTPS 传输并保存在面板服务器。请确保这把密钥已在宿主机 root 账号上获得授权。"); + const passphraseSaved = Boolean(hostConfig.private_key_passphrase_saved); + byId("host-private-key-passphrase").placeholder = passphraseSaved + ? "留空继续使用已保存的口令" : "输入用于解锁私钥的口令"; + text("host-passphrase-hint", passphraseSaved + ? "口令已加密保存且不会回显;私钥不变时留空可沿用,更换私钥时请填写新口令。" + : configured + ? "当前没有保存私钥口令。如私钥需要口令,请在此输入并重新保存,供面板重启后自动连接和后台持续采样。" + : "保存时会加密写入面板数据库,供重启后自动连接和后台持续采样;面板不会回显口令或写入浏览器存储。"); + text("host-test-status", configured + ? `当前已保存 ${hostConfig.host}:${hostConfig.port},修改前请重新扫描并核对主机指纹。` + : "尚未测试连接"); + byId("host-test-status").classList.remove("success", "warning"); + byId("boot-screen").hidden = true; + byId("database-view").hidden = true; + byId("setup-view").hidden = true; + byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; + byId("unlock-view").hidden = true; + byId("dashboard-view").hidden = true; + byId("host-view").hidden = false; +} + +async function showDashboard(session) { + if (!state.admin && !state.approved) { showAccessWait("approval"); return; } + if (!state.admin && !state.hostReady) { showAccessWait("host"); return; } + state.updateReturnView = null; + state.csrfToken = session.csrf_token || ""; + state.username = session.username || "用户"; + text("current-username", state.username); + byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; + byId("database-view").hidden = true; + byId("setup-view").hidden = true; + byId("host-view").hidden = true; + byId("unlock-view").hidden = true; + byId("boot-screen").hidden = true; + byId("dashboard-view").hidden = false; + showVmWorkspace(); + await Promise.allSettled([loadVMs(), loadResources()]); + if (byId("dashboard-view").hidden) return; + resumeReinstallJob(); + stopPolling(); + state.pollTimer = window.setInterval(() => { + if (!document.hidden) void loadVMs(true); + }, 15000); +} + +function applySession(session) { + state.sessionEpoch += 1; + state.templates = []; + state.rescueTemplates = []; + state.sshKeys = []; + state.sshKeysLoad = null; + fillSshKeyCards([]); + byId("ssh-keys-list").replaceChildren(); + byId("ssh-key-form").reset(); + showError("ssh-key-form-error", ""); + showError("ssh-keys-list-error", ""); + state.csrfToken = session.csrf_token || ""; + state.username = session.username || "用户"; + state.admin = session.admin === true; + state.approved = session.approved === true; + state.hostReady = session.host_ready === true; + fillTemplateViews([]); + if (!state.admin) clearAdminContent(); + for (const id of ["template-settings-button", "template-settings-mobile-button", "rescue-templates-button", "rescue-templates-mobile-button", "host-settings-button", "host-settings-mobile-button", "update-settings-button", "update-settings-mobile-button", "smtp-settings-button", "smtp-settings-mobile-button", "host-update-button", "unlock-update-button", "unlock-settings-button"]) { + byId(id).hidden = !state.admin; + } + byId("admin-menu").hidden = false; + byId("admin-menu").open = false; + text("current-username", state.username); +} + +async function continueAfterLogin(session) { + applySession(session); + if (!state.admin) { + state.hostConfig = null; + if (!state.approved) { showAccessWait("approval"); return; } + if (!state.hostReady) { showAccessWait("host"); return; } + await showDashboard(session); + return; + } + const hostConfig = await api("/api/v1/host"); + state.hostConfig = hostConfig || { configured: false }; + if (hostConfig?.configured && hostConfig?.key_locked) showUnlockView(hostConfig); + else if (hostConfig?.configured) await showDashboard(session); + else showHostView(hostConfig || { configured: false }); +} + +async function initialize() { + try { + const database = await api("/api/v1/database/status"); + if (database?.setup_required) { showDatabaseView(); return; } + const setup = await api("/api/v1/setup/status"); + if (setup?.setup_required) { showSetup(); return; } + const session = await api("/api/v1/session"); + if (session?.authenticated) await continueAfterLogin(session); + else showLogin(); + } catch (error) { + showLogin(); + showError("login-error", error.message); + } +} + +function resetCreatePage() { + byId("create-form").reset(); + byId("vm-template").value = ""; + renderTemplateCatalog("vm-template"); + clearSshKeyPicker("vm-guest-ssh-key-cards"); + byId("vm-root-password").value = ""; + updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); + showError("create-error", ""); +} + +function resetReinstallPage() { + state.reinstallPollToken += 1; + state.reinstallTarget = null; + state.reinstallJobId = null; + state.reinstallInProgress = false; + state.reinstallExpectGeneratedPassword = false; + state.reinstallPasswordPendingAck = false; + byId("reinstall-form").reset(); + byId("reinstall-template").value = ""; + renderTemplateCatalog("reinstall-template"); + clearSshKeyPicker("reinstall-ssh-key-cards"); + byId("reinstall-root-password").value = ""; + updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); + byId("reinstall-generated-password").textContent = ""; + showError("reinstall-error", ""); +} + +function canLeaveReinstallPage() { + if (byId("dashboard-view").hidden || byId("vm-workspace").hidden || byId("reinstall-view").hidden) return true; + if (state.reinstallPasswordPendingAck) { + toast("请先保存 root 密码,再点击“已保存密码,完成”确认清除。", "error"); + return false; + } + if (state.reinstallInProgress) { + toast("重装正在进行,请保持此页面打开,以免错过一次性显示的 root 密码。", "error"); + return false; + } + return true; +} + +function discardVmSubpageDrafts() { + if (!byId("create-view").hidden) resetCreatePage(); + if (!byId("reinstall-view").hidden) resetReinstallPage(); + if (!byId("rescue-view").hidden) { + byId("rescue-form").reset(); + byId("rescue-template-id").value = ""; + state.rescueTarget = null; + state.rescueActive = false; + state.rescueStaged = false; + state.rescuePowerState = "unknown"; + state.rescueCanExit = false; + state.rescueInProgress = false; + showError("rescue-error", ""); + state.rescuePollToken += 1; + } + state.sshKeysReturnView = null; +} + +function showVmSubpage(view) { + stopVmMetrics(); + clearVmCredential(); + byId("vm-list-view").hidden = true; + byId("vm-detail-view").hidden = true; + byId("create-view").hidden = view !== "create"; + byId("reinstall-view").hidden = view !== "reinstall"; + byId("rescue-view").hidden = view !== "rescue"; + text("breadcrumb-current", view === "create" ? "创建虚拟机" : view === "reinstall" ? "重装系统" : "紧急救援"); + window.scrollTo({ top: 0, behavior: "auto" }); + byId(view === "create" ? "create-title" : view === "reinstall" ? "reinstall-title" : "rescue-title").focus(); +} + +function showVmWorkspace({ preserveDraft = false } = {}) { + if (!state.admin && (!state.approved || !state.hostReady)) { + showAccessWait(state.approved ? "host" : "approval"); + return false; + } + if (!canLeaveReinstallPage()) return false; + byId("admin-menu").open = false; + stopVmMetrics(); + clearVmCredential(); + if (!preserveDraft) discardVmSubpageDrafts(); + state.selectedVmId = null; + byId("vm-workspace").hidden = false; + byId("vm-list-view").hidden = false; + byId("vm-detail-view").hidden = true; + byId("create-view").hidden = true; + byId("reinstall-view").hidden = true; + byId("rescue-view").hidden = true; + byId("ssh-keys-workspace").hidden = true; + byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; + byId("update-workspace").hidden = true; + byId("smtp-workspace").hidden = true; + byId("smtp-password").value = ""; + byId("vm-navigation-button").classList.add("active"); + byId("vm-navigation-button").setAttribute("aria-current", "page"); + byId("ssh-keys-button").classList.remove("active"); + byId("ssh-keys-button").removeAttribute("aria-current"); + byId("template-settings-button").classList.remove("active"); + byId("template-settings-button").removeAttribute("aria-current"); + byId("rescue-templates-button").classList.remove("active"); + byId("rescue-templates-button").removeAttribute("aria-current"); + byId("update-settings-button").classList.remove("active"); + byId("update-settings-button").removeAttribute("aria-current"); + byId("smtp-settings-button").classList.remove("active"); + byId("smtp-settings-button").removeAttribute("aria-current"); + text("breadcrumb-current", "虚拟机"); + window.scrollTo({ top: 0, behavior: "auto" }); + return true; +} + +async function showSshKeysWorkspace(returnView = null) { + if (!state.csrfToken) return; + if (!canLeaveReinstallPage()) return; + if (returnView === "create" || returnView === "reinstall") { + const passwordId = returnView === "create" ? "vm-root-password" : "reinstall-root-password"; + const hintId = returnView === "create" ? "vm-root-password-hint" : "reinstall-root-password-hint"; + if (byId(passwordId).value) { + byId(passwordId).value = ""; + updateRootPasswordHint(passwordId, hintId); + toast("已清空未提交的 root 密码;返回后请重新填写。", "info"); + } + } else discardVmSubpageDrafts(); + state.sshKeysReturnView = returnView; + byId("access-wait-view").hidden = true; + byId("dashboard-view").hidden = false; + byId("admin-menu").open = false; + state.updateReturnView = null; + stopVmMetrics(); + clearVmCredential(); + if (returnView !== "reinstall") state.selectedVmId = null; + byId("vm-workspace").hidden = true; + byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; + byId("update-workspace").hidden = true; + byId("smtp-workspace").hidden = true; + byId("smtp-password").value = ""; + byId("ssh-keys-workspace").hidden = false; + for (const id of ["vm-navigation-button", "template-settings-button", "rescue-templates-button", "update-settings-button", "smtp-settings-button"]) { + byId(id).classList.remove("active"); + byId(id).removeAttribute("aria-current"); + } + byId("ssh-keys-button").classList.add("active"); + byId("ssh-keys-button").setAttribute("aria-current", "page"); + text("breadcrumb-current", "公钥管理"); + showError("ssh-key-form-error", ""); + showError("ssh-keys-list-error", ""); + if (!state.sshKeys.length) byId("ssh-keys-list").replaceChildren(makeElement("p", "muted", "正在加载…")); + try { + await loadSshKeys(); + } catch (error) { + showError("ssh-keys-list-error", `无法读取公钥:${error.message}`); + } +} + +function returnFromSshKeysWorkspace() { + const returnView = state.sshKeysReturnView; + if (!returnView) { + showVmWorkspace(); + return; + } + state.sshKeysReturnView = null; + if (!showVmWorkspace({ preserveDraft: true })) return; + showVmSubpage(returnView); + if (returnView === "create") updateCreateSource(); + else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); +} + +async function showTemplateWorkspace() { + if (!state.admin || !state.csrfToken) return; + if (!canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); + byId("admin-menu").open = false; + stopVmMetrics(); + clearVmCredential(); + state.selectedVmId = null; + byId("vm-workspace").hidden = true; + byId("ssh-keys-workspace").hidden = true; + byId("update-workspace").hidden = true; + byId("smtp-workspace").hidden = true; + byId("smtp-password").value = ""; + byId("template-workspace").hidden = false; + byId("rescue-templates-workspace").hidden = true; + for (const id of ["vm-navigation-button", "ssh-keys-button", "rescue-templates-button", "update-settings-button", "smtp-settings-button"]) { + byId(id).classList.remove("active"); + byId(id).removeAttribute("aria-current"); + } + byId("template-settings-button").classList.add("active"); + byId("template-settings-button").setAttribute("aria-current", "page"); + text("breadcrumb-current", "云镜像模板"); + showError("template-import-error", ""); + showError("template-list-error", ""); + showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板;点击“导入模板”继续查询任务状态。" : ""); + byId("template-admin-list").replaceChildren(makeElement("p", "muted", "正在加载…")); + window.scrollTo({ top: 0, behavior: "auto" }); + try { + await loadTemplates(); + } catch (error) { + showError("template-list-error", `无法读取云镜像模板:${error.message}`); + byId("template-admin-list").replaceChildren(); + } +} + +function rescueImportStorageKey() { + return `${RESCUE_IMPORT_STORAGE_PREFIX}${state.username}`; +} + +function rescueJobStorageKey(uuid) { + return `${RESCUE_JOB_STORAGE_PREFIX}${state.username}:${uuid}`; +} + +function storedRescueJob(uuid) { + try { return sessionStorage.getItem(rescueJobStorageKey(uuid)) || ""; } catch { return ""; } +} + +function saveRescueJob(uuid, jobId) { + try { sessionStorage.setItem(rescueJobStorageKey(uuid), jobId); } catch { /* Status remains visible in this tab. */ } +} + +function formatRescueSize(bytes) { + const count = Number(bytes); + if (!Number.isFinite(count) || count < 0) return "大小未知"; + return count >= 1024 ** 3 ? `${(count / 1024 ** 3).toFixed(2)} GiB` : `${(count / 1024 ** 2).toFixed(1)} MiB`; +} + +function renderRescueTemplateCards() { + const cards = byId("rescue-template-cards"); + const selectedId = byId("rescue-template-id").value; + cards.replaceChildren(); + if (!state.rescueTemplates.length) { + cards.append(makeElement("p", "template-catalog-empty", state.admin + ? "还没有救援 ISO。请先在“救援模版”页面上传。" + : "还没有可用的救援 ISO,请联系管理员上传。")); + return; + } + for (const item of state.rescueTemplates) { + const id = String(item.id || ""); + if (!id) continue; + const card = makeElement("button", "rescue-template-card"); + card.type = "button"; + card.dataset.templateId = id; + card.setAttribute("aria-pressed", String(id === selectedId)); + card.append(makeElement("span", "rescue-template-symbol", "✚"), + makeElement("strong", "", item.name || id), + makeElement("small", "", `ISO · ${formatRescueSize(item.size_bytes)}`)); + card.addEventListener("click", () => { + byId("rescue-template-id").value = id; + cards.querySelectorAll(".rescue-template-card").forEach((option) => { + option.setAttribute("aria-pressed", String(option.dataset.templateId === id)); + }); + showError("rescue-error", ""); + }); + cards.append(card); + } +} + +function renderRescueTemplateList() { + const list = byId("rescue-template-list"); + list.replaceChildren(); + if (!state.admin) return; + if (!state.rescueTemplates.length) { + list.append(makeElement("p", "muted", "尚未上传救援 ISO。")); + return; + } + for (const item of state.rescueTemplates) { + const id = String(item.id || ""); + if (!id) continue; + const row = makeElement("div", "rescue-template-row"); + const label = makeElement("div", "rescue-template-row-label"); + label.append(makeElement("strong", "", item.name || id), + makeElement("small", "", `ISO · ${formatRescueSize(item.size_bytes)}`)); + const remove = makeElement("button", "button button-outline small", "删除"); + remove.type = "button"; + remove.setAttribute("aria-label", `删除救援模版 ${item.name || id}`); + remove.addEventListener("click", async () => { + if (!window.confirm(`确定删除救援模版“${item.name || id}”?正在使用的镜像不能删除。`)) return; + setButtonBusy(remove, true, "正在删除…"); + showError("rescue-template-list-error", ""); + try { + await api(`/api/v1/rescue-templates/${encodeURIComponent(id)}`, { method: "DELETE" }); + await loadRescueTemplates(); + toast("救援模版已删除。", "success"); + } catch (error) { + showError("rescue-template-list-error", error.message); + } finally { + if (remove.isConnected) setButtonBusy(remove, false); + } + }); + row.append(label, remove); + list.append(row); + } +} + +async function loadRescueTemplates() { + const epoch = state.sessionEpoch; + const result = await api("/api/v1/rescue-templates"); + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + state.rescueTemplates = (Array.isArray(result?.templates) ? result.templates : []) + .filter((item) => item && (typeof item.id === "string" || Number.isSafeInteger(item.id))); + if (!state.rescueTemplates.some((item) => String(item.id) === byId("rescue-template-id").value)) { + byId("rescue-template-id").value = ""; + } + renderRescueTemplateCards(); + renderRescueTemplateList(); +} + +function showRescueImportStatus(message) { + const status = byId("rescue-template-upload-status"); + status.textContent = message; + status.hidden = !message; +} + +async function pollRescueImport(jobId, token) { + const button = byId("rescue-template-upload-button"); + for (let attempt = 0; attempt < 720 && token === state.rescueUploadPollToken; attempt += 1) { + try { + const job = await api(`/api/v1/rescue-templates/import-jobs/${encodeURIComponent(jobId)}`); + if (token !== state.rescueUploadPollToken) return; + if (job?.status === "completed") { + state.rescueImportJobId = null; + state.rescueUploading = false; + try { sessionStorage.removeItem(rescueImportStorageKey()); } catch { /* Ignore private browsing limits. */ } + showRescueImportStatus("救援 ISO 已上传并导入宿主机。"); + byId("rescue-template-upload-form").reset(); + setButtonBusy(button, false); + button.textContent = "上传并导入"; + await loadRescueTemplates(); + toast("救援模版导入成功。", "success"); + return; + } + if (job?.status === "failed") { + state.rescueImportJobId = null; + try { sessionStorage.removeItem(rescueImportStorageKey()); } catch { /* Ignore private browsing limits. */ } + throw new Error(job.error || "救援 ISO 导入失败,请检查宿主机空间与文件格式。"); + } + if (job?.status !== "queued" && job?.status !== "running") throw new Error("救援模版任务状态未知,请稍后重试查询。"); + showRescueImportStatus(job.phase || (job.status === "queued" ? "等待宿主机导入救援 ISO…" : "宿主机正在导入救援 ISO…")); + } catch (error) { + if (token !== state.rescueUploadPollToken) return; + state.rescueUploading = false; + showError("rescue-template-upload-error", error.message); + setButtonBusy(button, false); + button.textContent = state.rescueImportJobId ? "继续查询导入状态" : "上传并导入"; + return; + } + await new Promise((resolve) => window.setTimeout(resolve, 5000)); + } + if (token === state.rescueUploadPollToken) { + state.rescueUploading = false; + showRescueImportStatus("导入仍未确认完成。请刷新页面后返回“救援模版”查看任务状态,不要重复上传。"); + setButtonBusy(button, false); + button.textContent = "继续查询导入状态"; + } +} + +async function showRescueTemplatesWorkspace() { + if (!state.admin || !state.csrfToken || !canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); + byId("admin-menu").open = false; + stopVmMetrics(); + clearVmCredential(); + state.selectedVmId = null; + for (const id of ["vm-workspace", "ssh-keys-workspace", "template-workspace", "update-workspace", "smtp-workspace"]) byId(id).hidden = true; + byId("rescue-templates-workspace").hidden = false; + for (const id of ["vm-navigation-button", "ssh-keys-button", "template-settings-button", "update-settings-button", "smtp-settings-button"]) { + byId(id).classList.remove("active"); + byId(id).removeAttribute("aria-current"); + } + byId("rescue-templates-button").classList.add("active"); + byId("rescue-templates-button").setAttribute("aria-current", "page"); + text("breadcrumb-current", "救援模版"); + const rescueIsoPool = String(state.hostConfig?.rescue_iso_pool || "").trim(); + text("rescue-directory-note", rescueIsoPool + ? `救援 ISO 专用目录或存储池:${rescueIsoPool}。上传的镜像不会列入创建虚拟机的安装 ISO 选项。` + : "尚未配置救援 ISO 专用目录。请先在“宿主机设置”填写已存在的救援目录并保存,然后再上传镜像。"); + byId("rescue-directory-note").hidden = false; + showError("rescue-template-upload-error", ""); + showError("rescue-template-list-error", ""); + byId("rescue-template-list").replaceChildren(makeElement("p", "muted", "正在加载…")); + window.scrollTo({ top: 0, behavior: "auto" }); + try { await loadRescueTemplates(); } catch (error) { showError("rescue-template-list-error", error.message); } + if (!state.rescueUploading) { + let jobId = state.rescueImportJobId; + if (!jobId) { + try { jobId = sessionStorage.getItem(rescueImportStorageKey()) || ""; } catch { jobId = ""; } + } + if (jobId) { + state.rescueImportJobId = jobId; + state.rescueUploading = true; + setButtonBusy(byId("rescue-template-upload-button"), true, "正在导入…"); + void pollRescueImport(jobId, ++state.rescueUploadPollToken); + } + } +} + +function selectedSshKeyId(containerId) { + return byId(containerId).querySelector('.ssh-key-option[aria-pressed="true"]')?.dataset.keyId || ""; +} + +function clearSshKeyPicker(containerId) { + byId(containerId).querySelectorAll(".ssh-key-option").forEach((option) => option.setAttribute("aria-pressed", "false")); +} + +function renderSshKeyPicker(containerId, items) { + const container = byId(containerId); + const previous = selectedSshKeyId(containerId); + const available = items.filter((item) => Number.isSafeInteger(Number(item?.id)) && Number(item.id) > 0); + const selected = available.some((item) => String(item.id) === previous) ? previous : ""; + const cards = available.map((item) => { + const button = makeElement("button", "ssh-key-option"); + button.type = "button"; + button.dataset.keyId = String(item.id); + button.setAttribute("aria-pressed", String(button.dataset.keyId === selected)); + button.append(makeElement("strong", "", String(item.name || `公钥 ${item.id}`))); + button.addEventListener("click", () => { + const wasSelected = button.getAttribute("aria-pressed") === "true"; + container.querySelectorAll(".ssh-key-option").forEach((option) => option.setAttribute("aria-pressed", "false")); + button.setAttribute("aria-pressed", String(!wasSelected)); + if (containerId === "vm-guest-ssh-key-cards") updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); + else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); + }); + return button; + }); + if (!available.length) { + cards.push(makeElement("p", "ssh-key-picker-empty", "还没有保存 SSH 公钥。可点击下方“管理我的公钥”先添加。")); + } + container.replaceChildren(...cards); + if (containerId === "vm-guest-ssh-key-cards") updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); + else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); +} + +function fillSshKeyCards(items) { + renderSshKeyPicker("vm-guest-ssh-key-cards", items); + renderSshKeyPicker("reinstall-ssh-key-cards", items); +} + +function sshKeyCreatedAt(value) { + if (value === null || value === undefined || value === "") return "未记录"; + const parsed = typeof value === "number" ? new Date(value * 1000) : new Date(value); + return Number.isFinite(parsed.getTime()) ? parsed.toLocaleString() : "未记录"; +} + +function renderSshKeys() { + const list = byId("ssh-keys-list"); + list.replaceChildren(); + if (!state.sshKeys.length) { + list.append(makeElement("p", "muted", "还没有保存公钥。导入后,创建云镜像虚拟机时即可直接选择。")); + return; + } + for (const key of state.sshKeys) { + const row = makeElement("div", "ssh-key-row"); + const details = makeElement("div", "ssh-key-details"); + details.append(makeElement("strong", "", key.name || `公钥 ${key.id}`)); + details.append(makeElement("code", "", key.fingerprint || "指纹未记录")); + details.append(makeElement("small", "", `添加时间:${sshKeyCreatedAt(key.created_at)}`)); + const actions = makeElement("div", "ssh-key-actions"); + const copy = makeElement("button", "button button-outline small", "复制公钥"); + copy.type = "button"; + copy.disabled = !key.public_key; + copy.addEventListener("click", async () => { + try { + await copyText(key.public_key); + toast("公钥已复制。", "success"); + } catch (error) { + toast(error.message, "error"); + } + }); + const remove = makeElement("button", "button button-outline small ssh-key-delete", "删除"); + remove.type = "button"; + remove.addEventListener("click", async () => { + if (!window.confirm(`确定删除公钥“${key.name}”?已经创建的虚拟机不会受影响。`)) return; + showError("ssh-keys-list-error", ""); + setButtonBusy(remove, true, "删除中…"); + try { + await api(`/api/v1/ssh-keys/${encodeURIComponent(String(key.id))}`, { method: "DELETE" }); + await loadSshKeys(); + toast("公钥已删除。", "success"); + } catch (error) { + showError("ssh-keys-list-error", error.message); + } finally { + if (remove.isConnected) setButtonBusy(remove, false); + } + }); + actions.append(copy, remove); + row.append(details, actions); + list.append(row); + } +} + +async function loadSshKeys() { + if (state.sshKeysLoad) return state.sshKeysLoad; + const epoch = state.sessionEpoch; + const request = api("/api/v1/ssh-keys"); + state.sshKeysLoad = request; + try { + const result = await request; + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + state.sshKeys = (Array.isArray(result?.items) ? result.items : []).filter((item) => { + const id = Number(item?.id); + return Number.isSafeInteger(id) && id > 0; + }); + fillSshKeyCards(state.sshKeys); + renderSshKeys(); + } finally { + if (state.sshKeysLoad === request) state.sshKeysLoad = null; + } +} + +function openUpdateFromGate(returnView) { + if (!state.admin) return; + if (returnView === "host") { + const hasKeyInput = Boolean(byId("host-private-key").value || state.uploadedPrivateKey || byId("host-private-key-passphrase").value); + if (hasKeyInput && !window.confirm("切换到网站更新会清空尚未保存的 SSH 私钥与口令输入。确定继续吗?")) return; + clearHostPrivateKey(); + } else if (returnView === "unlock") { + byId("unlock-passphrase").value = ""; + } + state.updateReturnView = returnView; + text("current-username", state.username || "管理员"); + byId("host-view").hidden = true; + byId("unlock-view").hidden = true; + byId("dashboard-view").hidden = false; + void showUpdateWorkspace(); +} + +function leaveUpdateWorkspace() { + byId("update-access-token").value = ""; + const returnView = state.updateReturnView; + if (returnView === "host" || returnView === "unlock") { + state.updateReturnView = null; + byId("dashboard-view").hidden = true; + byId("host-view").hidden = returnView !== "host"; + byId("unlock-view").hidden = returnView !== "unlock"; + return; + } + showVmWorkspace(); +} + +async function showUpdateWorkspace() { + if (!state.admin) return; + if (!canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); + byId("admin-menu").open = false; + stopVmMetrics(); + clearVmCredential(); + byId("vm-workspace").hidden = true; + byId("ssh-keys-workspace").hidden = true; + byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; + byId("smtp-workspace").hidden = true; + byId("smtp-password").value = ""; + byId("update-workspace").hidden = false; + byId("vm-navigation-button").classList.remove("active"); + byId("vm-navigation-button").removeAttribute("aria-current"); + byId("ssh-keys-button").classList.remove("active"); + byId("ssh-keys-button").removeAttribute("aria-current"); + byId("template-settings-button").classList.remove("active"); + byId("template-settings-button").removeAttribute("aria-current"); + byId("rescue-templates-button").classList.remove("active"); + byId("rescue-templates-button").removeAttribute("aria-current"); + byId("update-settings-button").classList.add("active"); + byId("update-settings-button").setAttribute("aria-current", "page"); + byId("smtp-settings-button").classList.remove("active"); + byId("smtp-settings-button").removeAttribute("aria-current"); + text("breadcrumb-current", "网站更新"); + showError("update-settings-error", ""); + if (!state.updateLastShownJobId && !state.updateJobId) showError("update-action-error", ""); + try { + await loadUpdateSettings(); + } catch (error) { + showError("update-settings-error", `无法读取更新设置:${error.message}`); + } +} + +async function loadSmtpSettings() { + const epoch = state.sessionEpoch; + const settings = await api("/api/v1/smtp/settings"); + if (epoch !== state.sessionEpoch || !state.admin) return; + byId("smtp-host").value = settings?.host || ""; + byId("smtp-port").value = settings?.port || 465; + byId("smtp-tls-mode").value = settings?.tls_mode || "ssl"; + byId("smtp-username").value = settings?.username || ""; + byId("smtp-from-address").value = settings?.from_address || ""; + byId("smtp-password").value = ""; + byId("smtp-password").placeholder = settings?.password_configured ? "留空沿用已保存的密码" : "填写 SMTP 密码或应用专用密码"; + text("smtp-password-hint", settings?.password_configured + ? "密码已加密保存;留空沿用现有密码。已保存密码不会回显,也不会写入浏览器存储。" + : "保存后不会回显,也不会写入浏览器存储。"); + text("smtp-status", settings?.configured ? "邮件服务已配置,可发送注册验证码。" : "尚未配置邮件服务;注册验证码暂不可发送。"); + byId("smtp-status").hidden = false; +} + +async function loadPendingUsers() { + const epoch = state.sessionEpoch; + const result = await api("/api/v1/users/pending"); + if (epoch !== state.sessionEpoch || !state.admin) return; + const list = byId("pending-users-list"); + list.replaceChildren(); + const users = Array.isArray(result?.items) ? result.items : []; + if (!users.length) { + list.append(makeElement("p", "muted", "暂无待审核用户。")); + return; + } + for (const user of users) { + const id = Number(user?.id); + if (!Number.isSafeInteger(id) || id <= 0) continue; + const row = makeElement("div", "pending-user-row"); + const details = makeElement("div", "pending-user-details"); + details.append(makeElement("strong", "", user.username || `用户 ${id}`)); + details.append(makeElement("span", "", user.email || "")); + const createdAt = Number(user.created_at); + const createdDate = Number.isSafeInteger(createdAt) && createdAt > 0 ? new Date(createdAt * 1000) : null; + const created = createdDate && Number.isFinite(createdDate.getTime()) + ? vmCreatedAt({ created_at: createdDate.toISOString() }) : "未记录"; + details.append(makeElement("small", "", `注册时间:${created}`)); + const button = makeElement("button", "button button-outline small", "审核通过"); + button.type = "button"; + button.addEventListener("click", async () => { + if (!window.confirm(`确认通过用户 ${String(user.username || id)} 的审核?通过后该用户可创建并管理自己的虚拟机。`)) return; + setButtonBusy(button, true, "正在审核…"); + showError("pending-users-error", ""); + try { + const approved = await api(`/api/v1/users/${encodeURIComponent(String(id))}/approve`, { method: "POST" }); + if (approved?.approved !== true) throw new Error("无法确认审核结果,请刷新待审核列表。"); + toast("用户审核通过。", "success"); + await loadPendingUsers(); + } catch (error) { + showError("pending-users-error", error.message); + } finally { + setButtonBusy(button, false); + } + }); + row.append(details, button); + list.append(row); + } +} + +async function showSmtpWorkspace() { + if (!state.admin) return; + if (!canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); + byId("admin-menu").open = false; + stopVmMetrics(); + clearVmCredential(); + byId("vm-workspace").hidden = true; + byId("ssh-keys-workspace").hidden = true; + byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; + byId("update-workspace").hidden = true; + byId("smtp-workspace").hidden = false; + byId("vm-navigation-button").classList.remove("active"); + byId("vm-navigation-button").removeAttribute("aria-current"); + byId("ssh-keys-button").classList.remove("active"); + byId("ssh-keys-button").removeAttribute("aria-current"); + byId("template-settings-button").classList.remove("active"); + byId("template-settings-button").removeAttribute("aria-current"); + byId("rescue-templates-button").classList.remove("active"); + byId("rescue-templates-button").removeAttribute("aria-current"); + byId("update-settings-button").classList.remove("active"); + byId("update-settings-button").removeAttribute("aria-current"); + byId("smtp-settings-button").classList.add("active"); + byId("smtp-settings-button").setAttribute("aria-current", "page"); + text("breadcrumb-current", "邮件与用户审核"); + showError("smtp-error", ""); + showError("pending-users-error", ""); + const [settingsResult, usersResult] = await Promise.allSettled([loadSmtpSettings(), loadPendingUsers()]); + if (settingsResult.status === "rejected") showError("smtp-error", `无法读取邮件设置:${settingsResult.reason.message}`); + if (usersResult.status === "rejected") showError("pending-users-error", `无法读取待审核用户:${usersResult.reason.message}`); +} + +async function loadUpdateSettings() { + const settings = await api("/api/v1/update/settings"); + state.updateCheck = null; + state.updateSettings = { configured: Boolean(settings?.configured), token_configured: Boolean(settings?.token_configured) }; + byId("update-repository-url").value = UPDATE_REPOSITORY_URL; + byId("update-branch").value = UPDATE_BRANCH; + byId("update-access-token").value = ""; + text("update-token-hint", settings?.token_configured + ? "访问令牌已保存;留空则继续使用现有令牌。令牌不会在页面回显。" + : "填写具有仓库读取权限的令牌。保存后不会回显,也不会写入浏览器存储。"); + if (settings?.current_version) text("update-current-version", settings.current_version); + byId("update-check-button").disabled = !settings?.configured || Boolean(settings?.active_job_id); + byId("update-apply-button").disabled = true; + if (settings?.checkout_error) text("update-status", settings.checkout_error); + else if (!settings?.token_configured) text("update-status", "请先保存私有仓库访问令牌,再检查更新。"); + const activeJobId = settings?.active_job_id; + if (activeJobId && activeJobId !== state.updateJobId) { + state.updateJobId = activeJobId; + void pollUpdateJob(activeJobId, ++state.updatePollToken); + return; + } + if (activeJobId) return; + const lastJobId = settings?.last_job_id; + if (lastJobId && lastJobId !== state.updateLastShownJobId) { + try { + const job = await api(`/api/v1/update/jobs/${encodeURIComponent(lastJobId)}`); + const status = String(job?.status || ""); + if (status === "succeeded" || status === "completed") { + state.updateLastShownJobId = lastJobId; + state.updateJobId = null; + state.updatePollToken += 1; + if (job?.new_commit) text("update-current-version", job.new_commit); + showError("update-action-error", ""); + text("update-status", "上次面板更新已完成。请确认虚拟机与宿主机连接正常。"); + } else if (status === "failed") { + state.updateLastShownJobId = lastJobId; + state.updateJobId = null; + state.updatePollToken += 1; + text("update-status", "上次面板更新未完成。"); + showError("update-action-error", String(job?.error || job?.message || "请检查独立更新服务日志。")); + } else if (status === "queued" || status === "running") { + state.updateJobId = lastJobId; + void pollUpdateJob(lastJobId, ++state.updatePollToken); + } + } catch (error) { + showError("update-action-error", `无法读取上次更新结果:${error.message}`); + } + } +} + +async function pollUpdateJob(jobId, token) { + let errors = 0; + for (let attempt = 0; attempt < 420; attempt += 1) { + if (token !== state.updatePollToken) return; + try { + const job = await api(`/api/v1/update/jobs/${encodeURIComponent(jobId)}`); + if (token !== state.updatePollToken) return; + errors = 0; + const status = String(job?.status || "running"); + const phase = String(job?.phase || job?.message || "正在更新面板文件…"); + text("update-status", `更新任务:${phase}`); + if (status === "succeeded" || status === "completed") { + text("update-status", "面板更新已完成。请刷新页面,并确认虚拟机与宿主机连接正常。"); + state.updateJobId = null; + state.updateLastShownJobId = jobId; + byId("update-check-button").disabled = false; + toast("面板更新已完成。", "success"); + return; + } + if (status === "failed") { + const message = String(job?.error || job?.message || "更新失败,请检查面板日志。"); + text("update-status", "更新未完成。"); + showError("update-action-error", message); + state.updateJobId = null; + state.updateLastShownJobId = jobId; + byId("update-check-button").disabled = false; + return; + } + } catch (error) { + if (token !== state.updatePollToken) return; + errors += 1; + text("update-status", `面板暂时无法响应(第 ${errors} 次),可能正在重启;将继续查询同一更新任务。`); + } + await new Promise((resolve) => window.setTimeout(resolve, 5000)); + } + if (token === state.updatePollToken) { + text("update-status", "暂时无法确认更新结果。请检查服务状态和日志,不要重复点击更新。"); + } +} + +function setButtonBusy(button, busy, busyLabel = "处理中…") { + if (busy) { + button.dataset.originalLabel = button.textContent; + button.textContent = busyLabel; + button.disabled = true; + } else { + button.textContent = button.dataset.originalLabel || button.textContent; + button.disabled = false; + } +} + +function saveReinstallJob(jobId) { + try { + sessionStorage.setItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`, JSON.stringify({ + job_id: jobId, + username: state.username, + expect_generated_password: state.reinstallExpectGeneratedPassword, + })); + } catch { /* Private browsing may disable session storage; the open page still tracks this job. */ } +} + +function clearSavedReinstallJob() { + try { sessionStorage.removeItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`); } catch { /* Storage is optional. */ } +} + +function readSavedReinstallJob() { + try { + const record = JSON.parse(sessionStorage.getItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`) || "null"); + if (!record || record.username !== state.username || !/^[0-9a-f-]{36}$/.test(record.job_id)) return null; + return record; + } catch { return null; } +} + +function setConnection(connected) { + text("host-connection-label", connected ? "连接正常" : "连接失败"); + byId("host-connection-dot").classList.toggle("offline", !connected); +} + +function hostCoordinates() { + return { + host: byId("host-address").value.trim(), + port: Number(byId("host-port").value), + }; +} + +function requireSecureCredentialTransport() { + if (location.protocol === "https:") return; + throw new Error("不能通过明文 HTTP 提交密码或 root 私钥。请通过你配置的 HTTPS 反向代理访问面板。"); +} + +function hostPayload() { + if (!byId("host-form").reportValidity()) return null; + const { host, port } = hostCoordinates(); + const scan = state.scannedHost; + if (!scan || scan.host !== host || Number(scan.port) !== port || !byId("host-fingerprint-confirm").checked) { + throw new Error("请先扫描主机指纹,并在宿主机控制台独立核对后勾选确认。"); + } + const privateKey = byId("host-private-key").value.trim() || state.uploadedPrivateKey.trim(); + if (!privateKey && !state.hostConfig?.private_key_configured) { + throw new Error("首次连接需要提供宿主机 root 账号已有的 SSH 私钥。"); + } + const isoPool = byId("host-iso-pool").value.trim(); + const rescueIsoPool = byId("host-rescue-iso-pool").value.trim(); + if (rescueIsoPool && rescueIsoPool === isoPool) { + throw new Error("救援 ISO 目录必须与安装 ISO 目录不同,避免救援镜像出现在创建虚拟机的安装镜像列表中。"); + } + const publicPoolCidr = byId("host-public-pool-cidr").value.trim(); + const publicGateway = byId("host-public-gateway").value.trim(); + const publicVmPrefixText = byId("host-public-vm-prefix").value.trim(); + const publicVmPrefix = publicVmPrefixText ? Number(publicVmPrefixText) : null; + const publicDnsServers = byId("host-public-dns").value.split(/[\s,;]+/).filter(Boolean); + const publicReservedIps = [...new Set(byId("host-public-reserved").value.split(/[\s,;]+/).filter(Boolean))]; + if (!publicPoolCidr && (publicGateway || publicVmPrefix !== null || publicDnsServers.length || publicReservedIps.length)) { + throw new Error("填写公网网关、虚拟机网卡前缀、DNS 或保留地址时,必须先填写服务商分配的公网网段;如需关闭地址池,请将这些项全部清空。"); + } + if (publicPoolCidr) { + const pool = parsePublicPool(publicPoolCidr); + if (!pool) { + throw new Error("公网地址池请填写服务商实际分配的 IPv4 网段(/24 至 /30),例如 123.123.123.112/28;/28 可填段内网关/前缀并自动换算,/24 必须填写网段起始地址。"); + } + if (publicVmPrefix !== null && (!Number.isInteger(publicVmPrefix) || publicVmPrefix < 24 || publicVmPrefix > pool.prefix)) { + throw new Error(`虚拟机网卡前缀须介于 /24 和地址池前缀 /${pool.prefix} 之间;留空则使用 /${pool.prefix}。`); + } + if (!validPoolMember(publicGateway, publicPoolCidr)) { + throw new Error("公网地址池网关必须是该网段内有效的 IPv4 地址,且不能是网段或广播地址。"); + } + if (publicDnsServers.length < 1 || publicDnsServers.length > 4 || !publicDnsServers.every((address) => ipv4Parts(address))) { + throw new Error("公网地址池需配置 1 至 4 个有效的 DNS IPv4 地址。"); + } + if (!publicReservedIps.every((address) => validPoolMember(address, publicPoolCidr))) { + throw new Error("额外保留的 IP 必须是该网段内的有效主机地址,不能填写网段或广播地址。"); + } + } + return { + host, + port, + region: byId("host-region").value.trim(), + private_key: privateKey, + private_key_passphrase: byId("host-private-key-passphrase").value, + host_key: scan.known_hosts_line, + confirmed_fingerprint: scan.fingerprint, + storage_pool: byId("host-storage-pool").value.trim(), + iso_pool: isoPool, + rescue_iso_pool: rescueIsoPool, + default_network: byId("host-network").value.trim(), + public_pool_cidr: publicPoolCidr, + public_gateway: publicGateway, + public_vm_prefix: publicVmPrefix, + public_dns_servers: publicDnsServers, + public_reserved_ips: publicReservedIps, + }; +} + +async function scanHost() { + showError("host-error", ""); + const { host, port } = hostCoordinates(); + if (!host || !Number.isInteger(port) || port < 1 || port > 65535) { + showError("host-error", "请先填写有效的宿主机地址和 SSH 端口。"); + return; + } + resetFingerprint(); + const button = byId("host-scan-button"); + setButtonBusy(button, true, "扫描中…"); + try { + const result = await api("/api/v1/host/scan", { method: "POST", body: { host, port } }); + const current = hostCoordinates(); + if (current.host !== host || current.port !== port) return; + if (!result?.fingerprint || !result?.known_hosts_line) throw new Error("扫描结果缺少主机公钥,请重试。"); + state.scannedHost = { ...result, host, port }; + text("host-key-type", result.key_type || "未知类型"); + text("host-fingerprint", result.fingerprint); + byId("host-fingerprint-result").hidden = false; + byId("host-confirm-row").hidden = false; + text("host-test-status", "扫描完成。请在宿主机控制台独立核对指纹,再勾选确认。"); + } catch (error) { + showError("host-error", `扫描失败:${error.message}`); + } finally { + setButtonBusy(button, false); + } +} + +async function submitHost(save) { + showError("host-error", ""); + const button = byId(save ? "host-save-button" : "host-test-button"); + try { + requireSecureCredentialTransport(); + const body = hostPayload(); + if (!body) return; + setButtonBusy(button, true, save ? "保存并连接中…" : "测试连接中…"); + const result = await api(save ? "/api/v1/host" : "/api/v1/host/test", { + method: save ? "PUT" : "POST", body, + }); + const warnings = resourceWarnings(result); + if (save) { + if (!result?.configured) throw new Error("宿主机配置未确认保存,请检查后重试。"); + state.hostConfig = result; + clearHostPrivateKey(); + await showDashboard({ username: state.username, csrf_token: state.csrfToken }); + if (warnings.length) { + const message = `宿主机已连接,但资源尚未就绪:${warnings.join(";")}`; + showResourceWarning(message); + toast(message); + } else { + toast("宿主机已连接,设置已保存。", "success"); + } + } else { + if (warnings.length) { + text("host-test-status", `root SSH 和 libvirt 连接成功,但资源尚未就绪:${warnings.join(";")}。仍可保存宿主机配置。`); + byId("host-test-status").classList.add("warning"); + byId("host-test-status").classList.remove("success"); + } else { + text("host-test-status", body.default_network.startsWith("bridge:") + ? "连接成功:root SSH、libvirt 和存储池可访问。现有网桥将在创建虚拟机时由宿主机验证;现在可以保存设置。" + : "连接成功:root SSH、libvirt、存储池和虚拟网络均可访问。现在可以保存设置。"); + byId("host-test-status").classList.add("success"); + byId("host-test-status").classList.remove("warning"); + } + } + } catch (error) { + byId("host-private-key-passphrase").value = ""; + text("host-test-status", "连接未完成,请检查错误信息。"); + byId("host-test-status").classList.remove("success", "warning"); + showError("host-error", error.message); + } finally { + setButtonBusy(button, false); + } +} + +async function submitUnlock() { + showError("unlock-error", ""); + const button = byId("unlock-submit"); + try { + requireSecureCredentialTransport(); + const passphrase = byId("unlock-passphrase").value; + if (!passphrase) throw new Error("请输入 SSH 私钥口令。"); + setButtonBusy(button, true, "解锁中…"); + const result = await api("/api/v1/host/unlock", { + method: "POST", body: { passphrase }, + }); + if (!result?.configured || result?.key_locked) throw new Error("私钥未解锁,请确认口令后重试。"); + const hostConfig = await api("/api/v1/host"); + if (!hostConfig?.configured || hostConfig?.key_locked) throw new Error("无法确认私钥已解锁,请重试。"); + state.hostConfig = hostConfig; + await showDashboard({ username: state.username, csrf_token: state.csrfToken }); + toast("宿主机私钥已解锁。", "success"); + } catch (error) { + showError("unlock-error", error.message); + } finally { + byId("unlock-passphrase").value = ""; + setButtonBusy(button, false); + } +} + +async function loadVMs(silent = false) { + if (state.loadingVMs || byId("dashboard-view").hidden) return; + state.loadingVMs = true; + const epoch = state.sessionEpoch; + const refreshButton = byId("refresh-button"); + const detailRefreshButton = byId("vm-detail-refresh-button"); + refreshButton.disabled = true; + detailRefreshButton.disabled = true; + try { + const result = await api("/api/v1/vms"); + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + state.vms = Array.isArray(result?.items) ? result.items : []; + setConnection(true); + renderVMs(); + syncVmDetailAfterRefresh(); + } catch (error) { + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + setConnection(false); + if (!silent && !byId("dashboard-view").hidden) toast(error.message, "error"); + if (!state.vms.length) renderVMs(true); + } finally { + refreshButton.disabled = false; + detailRefreshButton.disabled = false; + state.loadingVMs = false; + } +} + +function stateCategory(value) { + const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); + if (normalized === "running" || normalized === "blocked") return "running"; + if (["shutoff", "stopped", "crashed"].includes(normalized)) return "stopped"; + return "other"; +} + +function stateLabel(value) { + const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); + const labels = { + running: "运行中", blocked: "运行中", shutoff: "已关机", stopped: "已关机", + shutdown: "关机中", crashed: "已崩溃", paused: "已暂停", pmsuspended: "已挂起", + nostate: "未知", unknown: "未知", + }; + return labels[normalized] || String(value || "未知"); +} + +function diskLabel(vm) { + if (Array.isArray(vm.disks) && vm.disks.length) { + const size = vm.disks.reduce((sum, disk) => { + const capacity = Number(disk.capacity_gib ?? disk.size_gib ?? 0); + return sum + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0); + }, 0); + if (size > 0) return `${Math.round(size * 100) / 100} GiB`; + } + if (Number.isFinite(Number(vm.disk_gib)) && Number(vm.disk_gib) > 0) return `${vm.disk_gib} GiB`; + return "—"; +} + +function vmSystemInfo(vm) { + if (vm.os_source === "iso") return { label: "安装镜像", value: String(vm.install_iso || "未识别") }; + if (vm.os_source === "cloud_template") return { label: "系统镜像", value: String(vm.os_name || "未识别") }; + return { label: "系统", value: String(vm.os_name || "未识别") }; +} + +function vmRegion(vm) { + return String(vm.region || "").trim() || "未设置"; +} + +function vmIp(vm) { + return String(vm.public_ip_cidr || "").trim().split("/")[0] || "未获取"; +} + +function vmCreatedAt(vm) { + const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; + if (!value) return "未记录"; + const date = new Date(value); + if (!Number.isFinite(date.getTime())) return "未记录"; + const pad = (number) => String(number).padStart(2, "0"); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`; +} + +function vmCreatedAgo(vm, now = Date.now()) { + const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; + if (!value) return "未记录"; + const created = Date.parse(value); + if (!Number.isFinite(created)) return "未记录"; + const elapsed = Math.max(0, now - created); + const minute = 60 * 1000; + const hour = 60 * minute; + const day = 24 * hour; + const month = 30 * day; + if (elapsed < minute) return "创建于刚刚"; + if (elapsed < hour) return `创建于 ${Math.floor(elapsed / minute)} 分钟前`; + if (elapsed < day) return `创建于 ${Math.floor(elapsed / hour)} 小时前`; + if (elapsed < month) return `创建于 ${Math.floor(elapsed / day)} 天前`; + return `创建于 ${Math.floor(elapsed / month)} 个月前`; +} + +function makeCell(row, className = "") { + const cell = document.createElement("td"); + if (className) cell.className = className; + row.append(cell); + return cell; +} + +function makeElement(tag, className, content) { + const element = document.createElement(tag); + if (className) element.className = className; + if (content !== undefined) element.textContent = String(content); + return element; +} + +function makeCopyIconButton(value, label) { + const button = makeElement("button", "vm-copy-icon"); + button.type = "button"; + button.title = `复制${label}`; + button.setAttribute("aria-label", `复制${label}`); + const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + icon.setAttribute("viewBox", "0 0 24 24"); + icon.setAttribute("aria-hidden", "true"); + const back = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + for (const [name, attribute] of Object.entries({ x: "8", y: "8", width: "12", height: "12", rx: "2" })) { + back.setAttribute(name, attribute); + } + const front = document.createElementNS("http://www.w3.org/2000/svg", "path"); + front.setAttribute("d", "M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"); + icon.append(back, front); + button.append(icon); + button.addEventListener("click", async () => { + try { + await copyText(value); + toast(`${label}已复制。`, "success"); + } catch (error) { + toast(error.message, "error"); + } + }); + return button; +} + +function actionButton(label, handler, options = {}) { + const button = makeElement("button", `row-button ${options.variant || ""}`, label); + button.type = "button"; + button.disabled = Boolean(options.disabled); + if (options.key) button.dataset.vmAction = options.key; + if (options.title) button.title = options.title; + button.addEventListener("click", handler); + return button; +} + +function renderVMs(connectionError = false) { + const all = state.vms; + const runningCount = all.filter((vm) => stateCategory(vm.state) === "running").length; + const stoppedCount = all.filter((vm) => stateCategory(vm.state) === "stopped").length; + text("stat-total", String(all.length)); + text("stat-running", String(runningCount)); + text("stat-stopped", String(stoppedCount)); + + const query = byId("search-input").value.trim().toLocaleLowerCase(); + const filter = byId("state-filter").value; + const filtered = all.filter((vm) => { + const matchesText = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.region, vm.os_name, vm.install_iso] + .some((value) => String(value || "").toLocaleLowerCase().includes(query)); + return matchesText && (filter === "all" || stateCategory(vm.state) === filter); + }); + text("inventory-count", `${filtered.length} 台虚拟机${filtered.length !== all.length ? ` · 共 ${all.length} 台` : ""}`); + const tbody = byId("vm-table-body"); + const focusedVmId = document.activeElement?.classList.contains("vm-name-link") + ? document.activeElement.dataset.vmUuid : null; + tbody.replaceChildren(); + const empty = byId("empty-state"); + empty.hidden = filtered.length !== 0; + if (!filtered.length) { + if (connectionError) { + text("empty-title", "无法加载虚拟机"); + text("empty-description", "请检查面板与宿主机的连接,然后点击刷新。"); + } else if (all.length) { + text("empty-title", "没有匹配的虚拟机"); + text("empty-description", "尝试更换搜索词或状态筛选。"); + } else { + text("empty-title", "还没有虚拟机"); + text("empty-description", "点击右上角“创建虚拟机”开始。"); + } + return; + } + + for (const vm of filtered) { + const uuid = String(vm.uuid || ""); + const category = stateCategory(vm.state); + const row = document.createElement("tr"); + const identity = makeElement("div", "vm-identity"); + identity.append(makeElement("div", "vm-icon", "▣")); + const identityText = makeElement("div"); + const nameButton = makeElement("button", "vm-name-link", vm.name || "未命名虚拟机"); + nameButton.type = "button"; + nameButton.disabled = !uuid; + nameButton.dataset.vmUuid = uuid; + nameButton.setAttribute("aria-label", `管理虚拟机 ${vm.name || uuid}`); + nameButton.addEventListener("click", () => openVmDetail(uuid)); + identityText.append(nameButton); + const uuidRow = makeElement("span", "vm-uuid-row"); + const uuidText = makeElement("span", "vm-id", uuid || "UUID 未知"); + if (uuid) uuidText.title = uuid; + uuidRow.append(uuidText); + if (uuid) uuidRow.append(makeCopyIconButton(uuid, "UUID")); + identityText.append(uuidRow); + identity.append(identityText); + const identityCell = makeCell(row); + identityCell.dataset.label = "虚拟机"; + identityCell.append(identity); + + const stateCell = makeCell(row); + stateCell.dataset.label = "状态"; + stateCell.append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state))); + const regionCell = makeCell(row); + regionCell.dataset.label = "地区"; + regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm))); + const system = vmSystemInfo(vm); + const systemCell = makeCell(row); + systemCell.dataset.label = system.label; + systemCell.append(makeElement("span", "vm-metadata", system.value)); + const ipCell = makeCell(row); + ipCell.dataset.label = "已配置公网 IP"; + const ip = vmIp(vm); + const ipRow = makeElement("span", "vm-ip-copy-row"); + ipRow.append(makeElement("span", "vm-metadata vm-ip", ip)); + if (ip !== "未获取") ipRow.append(makeCopyIconButton(ip, "公网 IP")); + ipCell.append(ipRow); + const spec = makeElement("div", "vm-spec"); + spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`)); + spec.append(makeElement("small", "", "计算资源")); + const specCell = makeCell(row); + specCell.dataset.label = "规格"; + specCell.append(spec); + const diskCell = makeCell(row); + diskCell.dataset.label = "磁盘"; + diskCell.append(makeElement("span", "vm-spec", diskLabel(vm))); + tbody.append(row); + } + if (focusedVmId) { + const replacement = Array.from(tbody.querySelectorAll(".vm-name-link")) + .find((button) => button.dataset.vmUuid === focusedVmId); + replacement?.focus({ preventScroll: true }); + } +} + +function renderVmCredentialStatus(vm) { + const uuid = String(vm.uuid || ""); + const mode = String(vm.auth_mode || "unknown"); + const passwordAvailable = vm.password_available === true; + if (state.credentialVmId && (state.credentialVmId !== uuid || !passwordAvailable)) clearVmCredential(); + const knownRoot = vm.managed && (vm.os_source === "cloud_template" || mode === "password" || mode === "ssh_key" || mode === "ssh_key_password"); + text("vm-detail-ssh-user", knownRoot ? "root" : "未记录"); + const shown = passwordAvailable && state.credentialVmId === uuid && state.credentialVisible && !!state.credentialPassword; + text("vm-detail-root-password", passwordAvailable + ? (shown ? state.credentialPassword : "********") + : mode === "ssh_key" ? "SSH 公钥登录,无密码" : mode === "password" ? "未保存" : "未记录"); + const reveal = byId("vm-detail-password-reveal"); + const copy = byId("vm-detail-password-copy"); + reveal.hidden = !passwordAvailable; + copy.hidden = !passwordAvailable; + reveal.disabled = state.credentialBusy || !uuid; + copy.disabled = state.credentialBusy || !uuid; + const revealAction = state.credentialBusy ? "正在读取初始 root 密码…" + : shown ? "隐藏初始 root 密码" : "查看初始 root 密码"; + reveal.setAttribute("aria-label", revealAction); + reveal.setAttribute("aria-pressed", String(shown)); + reveal.title = revealAction; +} + +async function readVmCredential(uuid) { + const token = ++state.credentialRequestToken; + const result = await api(`/api/v1/vms/${encodeURIComponent(uuid)}/credential`, { method: "POST" }); + if (token !== state.credentialRequestToken || state.selectedVmId !== uuid || byId("vm-detail-view").hidden) return null; + if (result?.login_name !== "root" || typeof result?.password !== "string" || !result.password) { + throw new Error("这台虚拟机没有可查看的面板记录密码。"); + } + return result.password; +} + +function openVmDetail(uuid) { + const vm = state.vms.find((item) => String(item.uuid || "") === uuid); + if (!vm) { + toast("虚拟机已不在当前列表中,请刷新后重试。", "error"); + return; + } + stopVmMetrics(); + clearVmCredential(); + state.selectedVmId = uuid; + byId("vm-list-view").hidden = true; + byId("vm-detail-view").hidden = false; + byId("create-view").hidden = true; + byId("reinstall-view").hidden = true; + byId("rescue-view").hidden = true; + renderVmDetail(vm); + clearVmMetrics("正在加载监控数据…"); + startVmMetrics(); + window.scrollTo({ top: 0, behavior: "auto" }); + byId("vm-detail-name").focus(); +} + +function syncVmDetailAfterRefresh() { + if (!state.selectedVmId || byId("vm-workspace").hidden || byId("vm-detail-view").hidden) return; + const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId); + if (!vm) { + showVmWorkspace(); + toast("这台虚拟机已从宿主机移除,已返回列表。", "info"); + byId("vm-list-title").focus(); + return; + } + renderVmDetail(vm); +} + +function renderVmDetail(vm) { + const category = stateCategory(vm.state); + const running = category === "running"; + const stopped = category === "stopped"; + const shuttingDown = String(vm.state || "").toLowerCase().replace(/[_\s-]+/g, "") === "shutdown"; + const rescueMode = vm.rescue_mode === true; + const rescueStaged = vm.rescue_staged === true; + const rescueGuard = rescueMode || rescueStaged; + const uuid = String(vm.uuid || ""); + const busy = state.vmActionInFlight === uuid; + const system = vmSystemInfo(vm); + text("vm-detail-name", vm.name || "未命名虚拟机"); + text("vm-detail-state", stateLabel(vm.state)); + byId("vm-detail-state").className = `state-pill ${category}`; + const region = vmRegion(vm); + text("vm-detail-header-region", region); + text("vm-detail-header-created-at", vmCreatedAgo(vm)); + text("vm-detail-region", region); + text("vm-detail-os-label", system.label); + text("vm-detail-os", system.value); + const ip = vmIp(vm); + text("vm-detail-header-ip", ip); + text("vm-detail-ip", ip); + byId("vm-detail-ip-copy").hidden = ip === "未获取"; + text("vm-detail-spec", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`); + text("vm-detail-disk", diskLabel(vm)); + renderVmCredentialStatus(vm); + const hasConsole = Number(vm.console_port) > 0; + text("breadcrumb-current", vm.name || "虚拟机详情"); + + const primary = byId("vm-detail-primary-actions"); + const danger = byId("vm-detail-danger-actions"); + const focusedAction = document.activeElement?.dataset.vmAction || null; + primary.replaceChildren(); + danger.replaceChildren(); + primary.append(actionButton("打开 VNC 控制台", () => void openConsole(vm), { + disabled: busy || !running || !uuid || !hasConsole, + variant: "primary", + key: "console", + title: !running ? "虚拟机运行时可用" : hasConsole ? "打开 VNC 控制台" : "该虚拟机未配置 VNC 控制台", + })); + if (running) { + primary.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget), { disabled: busy || rescueGuard, key: "shutdown", title: rescueGuard ? "请在紧急救援页面处理启动介质" : "正常关机" })); + primary.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget), { disabled: busy || rescueGuard, key: "reboot", title: rescueGuard ? "请在紧急救援页面处理启动介质" : "重启虚拟机" })); + danger.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { disabled: busy || (rescueMode && !rescueStaged), variant: "danger", key: "poweroff", title: rescueStaged ? "救援 ISO 已预挂载;强制断电后再点开机" : rescueMode ? "请先退出救援模式" : "强制断电" })); + danger.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { disabled: busy || rescueGuard, variant: "danger", key: "reset", title: rescueStaged ? "强制重置不保证读取新保存的救援启动配置" : rescueMode ? "请先退出救援模式" : "强制重置" })); + } else if (shuttingDown) { + danger.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { disabled: busy || (rescueMode && !rescueStaged), variant: "danger", key: "poweroff", title: rescueStaged ? "救援 ISO 已预挂载;强制断电后再点开机" : rescueMode ? "请先退出救援模式" : "关机中仍可手动强制断电" })); + } else { + primary.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: busy || (rescueMode && !rescueStaged) || !stopped || !uuid, key: "start", title: rescueStaged ? "从已预挂载的救援 ISO 开机" : rescueMode ? "请先退出救援模式" : "启动虚拟机" })); + } + if (vm.managed && vm.public_ip_cidr) { + danger.append(actionButton("重装系统", () => openReinstall(vm), { + disabled: busy || rescueGuard || !uuid, + variant: "danger", + key: "reinstall", + title: "从云镜像模板重装,成功后自动删除旧系统盘", + })); + } + danger.append(actionButton("紧急救援", () => void openRescue(vm), { + disabled: busy || !uuid, + key: "rescue", + title: rescueStaged ? "救援 ISO 已预挂载;查看状态或取消救援" : "预挂载救援 ISO;运行中虚拟机会先正常关机,再从救援环境启动", + })); + danger.append(actionButton("删除虚拟机", () => openDelete(vm), { + disabled: busy || rescueGuard || !stopped || !uuid, + variant: "danger", + key: "delete", + title: rescueGuard ? "请先退出救援模式" : stopped ? "删除虚拟机" : "请先关机再删除", + })); + if (focusedAction) { + const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) + .find((button) => button.dataset.vmAction === focusedAction && !button.disabled); + replacement?.focus({ preventScroll: true }); + } +} + +const VM_METRICS_RANGE_SECONDS = { "1h": 3600, "24h": 86400, "7d": 604800, "30d": 2592000 }; +const VM_METRIC_CHARTS = [ + { id: "cpu", title: "CPU 使用率", unit: "percent", series: [{ key: "cpu_percent", color: "#0f9eaa" }] }, + { id: "memory", title: "内存用量", unit: "memory", series: [{ key: "memory_used_mib", color: "#4781cf" }, { key: "memory_total_mib", color: "#a4b7d7", dash: "6 5" }] }, + { id: "disk", title: "磁盘 I/O", unit: "rate", series: [{ key: "disk_read_bps", color: "#477dc9" }, { key: "disk_write_bps", color: "#e59c46" }] }, + { id: "network", title: "网络速率", unit: "rate", series: [{ key: "network_rx_bps", color: "#17a685" }, { key: "network_tx_bps", color: "#926ed0" }] }, +]; + +function metricViewVisible() { + return Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden + && !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden; +} + +function stopVmMetrics() { + if (state.metricsPollTimer) window.clearInterval(state.metricsPollTimer); + state.metricsPollTimer = null; + if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer); + state.metricsResizeTimer = null; + state.metricsRequest?.controller.abort(); + state.metricsRequest = null; +} + +function startVmMetrics() { + if (!metricViewVisible()) return; + void loadVmMetrics(); + if (!state.metricsPollTimer) { + state.metricsPollTimer = window.setInterval(() => { + if (metricViewVisible()) void loadVmMetrics(); + }, 60000); + } +} + +function setVmMetricsStatus(message, warning = false) { + const status = byId("vm-metrics-status"); + status.textContent = message; + status.classList.toggle("warning", warning); +} + +function clearVmMetrics(message) { + state.metricsPayload = null; + setVmMetricsStatus(message); + for (const chart of VM_METRIC_CHARTS) { + text(`vm-metric-${chart.id}-summary`, "—"); + byId(`vm-metric-${chart.id}-plot`).replaceChildren(makeElement("p", "vm-metric-empty", message)); + } +} + +async function loadVmMetrics() { + if (!metricViewVisible()) return; + const vmId = state.selectedVmId; + const range = state.metricsRange; + const previous = state.metricsRequest; + if (previous?.vmId === vmId && previous.range === range) return; + previous?.controller.abort(); + const request = { vmId, range, controller: new AbortController() }; + state.metricsRequest = request; + setVmMetricsStatus("正在更新监控数据…"); + try { + const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/metrics?range=${encodeURIComponent(range)}`, { + signal: request.controller.signal, + }); + if (request !== state.metricsRequest || !metricViewVisible()) return; + if (!Array.isArray(payload?.points) || (payload.vm_id && payload.vm_id !== vmId)) { + throw new Error("监控数据格式无效。"); + } + renderVmMetrics(payload); + } catch (error) { + if (request !== state.metricsRequest || request.controller.signal.aborted || !metricViewVisible()) return; + setVmMetricsStatus(`监控数据暂时无法加载:${error.message}。已显示的数据可能不是最新。`, true); + } finally { + if (request === state.metricsRequest) state.metricsRequest = null; + } +} + +function metricNumber(value) { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; +} + +function formatMetricRate(value) { + if (value === null) return "无统计"; + const units = ["B/s", "KB/s", "MB/s", "GB/s", "TB/s"]; + let amount = value; + let index = 0; + while (amount >= 1000 && index < units.length - 1) { amount /= 1000; index += 1; } + return `${amount.toFixed(index === 0 ? (amount < 1 && amount > 0 ? 2 : 0) : amount < 10 ? 2 : 1)} ${units[index]}`; +} + +function formatMetricMemory(value) { + if (value === null) return "无统计"; + return value >= 1024 ? `${(value / 1024).toFixed(value < 10240 ? 2 : 1)} GiB` : `${Math.round(value)} MiB`; +} + +function formatMetricValue(value, unit) { + if (value === null) return "无统计"; + if (unit === "percent") return `${value.toFixed(1)}%`; + if (unit === "memory") return formatMetricMemory(value); + return formatMetricRate(value); +} + +function formatMetricTime(timestamp) { + return new Date(timestamp * 1000).toLocaleString("zh-CN", { + month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", + }); +} + +function metricSummary(chart, points) { + const latest = [...points].reverse().find((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); + if (!latest) return "暂无统计"; + const value = (key) => metricNumber(latest[key]); + if (chart.id === "cpu") return formatMetricValue(value("cpu_percent"), "percent"); + if (chart.id === "memory") return `已使用(估算)${formatMetricMemory(value("memory_used_mib"))} · 总量 ${formatMetricMemory(value("memory_total_mib"))}`; + if (chart.id === "disk") return `读取 ${formatMetricRate(value("disk_read_bps"))} · 写入 ${formatMetricRate(value("disk_write_bps"))}`; + return `接收 ${formatMetricRate(value("network_rx_bps"))} · 发送 ${formatMetricRate(value("network_tx_bps"))}`; +} + +function metricChartEmptyText(chart) { + if (chart.id === "memory") return "暂无内存统计;虚拟机可能未提供气球驱动数据。"; + if (chart.id === "disk" || chart.id === "network") return "暂无速率数据;首次采样或停机时无法计算速率。"; + return "当前时间范围内暂无 CPU 采样数据。"; +} + +function metricNiceMax(value) { + if (value <= 0) return 1; + const base = 10 ** Math.floor(Math.log10(value)); + for (const step of [1, 1.5, 2, 2.5, 5, 10]) { + if (value <= step * base) return step * base; + } + return 10 * base; +} + +function metricSvgElement(tag, attributes = {}) { + const element = document.createElementNS("http://www.w3.org/2000/svg", tag); + for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value)); + return element; +} + +function drawMetricChart(chart, points, start, end, intervalSeconds) { + const plot = byId(`vm-metric-${chart.id}-plot`); + const summary = metricSummary(chart, points); + text(`vm-metric-${chart.id}-summary`, summary); + const hasData = points.some((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); + if (!hasData) { + plot.replaceChildren(makeElement("p", "vm-metric-empty", metricChartEmptyText(chart))); + return; + } + + const values = points.flatMap((point) => chart.series.map((series) => metricNumber(point[series.key]))).filter((value) => value !== null); + const maximum = chart.unit === "percent" ? Math.max(100, metricNiceMax(Math.max(...values))) : metricNiceMax(Math.max(...values)); + // A fixed 640px viewBox shrinks axis text to ~4px inside a phone card. + const width = Math.max(240, Math.floor(plot.clientWidth || 640)); + const height = Math.max(180, Math.floor(plot.clientHeight || 216)); + const left = 64; + const right = 18; + const top = 14; + const bottom = 37; + const plotWidth = width - left - right; + const plotHeight = height - top - bottom; + const x = (timestamp) => left + Math.max(0, Math.min(1, (timestamp - start) / (end - start))) * plotWidth; + const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight; + const svg = metricSvgElement("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": `${chart.title},${byId("vm-metrics-range").selectedOptions[0]?.textContent || "当前范围"};最近记录:${summary}` }); + for (const fraction of [1, 0.5, 0]) { + const lineY = top + (1 - fraction) * plotHeight; + svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" })); + const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" }); + label.textContent = formatMetricValue(fraction * maximum, chart.unit); + svg.append(label); + } + for (const [fraction, anchor] of [[0, "start"], [0.5, "middle"], [1, "end"]]) { + const label = metricSvgElement("text", { x: left + fraction * plotWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" }); + label.textContent = formatMetricTime(start + fraction * (end - start)); + svg.append(label); + } + + const maxGap = intervalSeconds * 2.5; + for (const series of chart.series) { + const segments = []; + let segment = []; + for (const point of points) { + const value = metricNumber(point[series.key]); + if (value === null) { + if (segment.length) segments.push(segment); + segment = []; + continue; + } + if (segment.length && point.timestamp - segment[segment.length - 1].timestamp > maxGap) { + segments.push(segment); + segment = []; + } + segment.push({ timestamp: point.timestamp, value }); + } + if (segment.length) segments.push(segment); + for (const group of segments) { + if (group.length > 1) { + const path = metricSvgElement("path", { + d: group.map((point, index) => `${index ? "L" : "M"}${x(point.timestamp).toFixed(2)} ${y(point.value).toFixed(2)}`).join(" "), + fill: "none", stroke: series.color, "stroke-width": 2.6, + "stroke-linecap": "round", "stroke-linejoin": "round", + ...(series.dash ? { "stroke-dasharray": series.dash } : {}), + }); + svg.append(path); + } + const last = group[group.length - 1]; + svg.append(metricSvgElement("circle", { cx: x(last.timestamp), cy: y(last.value), r: group.length === 1 ? 3.8 : 2.8, fill: series.color })); + } + } + plot.replaceChildren(svg); +} + +function renderVmMetrics(payload) { + state.metricsPayload = payload; + const intervalSeconds = Math.max(1, Number(payload.interval_seconds) || 60); + const rangeSeconds = VM_METRICS_RANGE_SECONDS[state.metricsRange]; + const now = Math.floor(Date.now() / 1000); + const points = payload.points + .filter((point) => Number.isFinite(Number(point?.timestamp)) && Number(point.timestamp) >= now - rangeSeconds - intervalSeconds && Number(point.timestamp) <= now + intervalSeconds) + .map((point) => ({ ...point, timestamp: Number(point.timestamp) })) + .sort((a, b) => a.timestamp - b.timestamp); + const end = Math.max(now, points.length ? points[points.length - 1].timestamp : now); + const start = end - rangeSeconds; + const visiblePoints = points.filter((point) => point.timestamp >= start && point.timestamp <= end); + for (const chart of VM_METRIC_CHARTS) drawMetricChart(chart, visiblePoints, start, end, intervalSeconds); + if (!visiblePoints.length) { + setVmMetricsStatus("当前时间范围内没有采样记录。虚拟机运行后,通常需等待下一次后台采样。", true); + return; + } + const latest = visiblePoints[visiblePoints.length - 1].timestamp; + // Bucket width grows for long ranges; freshness still follows the 60s + // collector cadence, not the downsampling bucket width. + const stale = end - latest > 60 * 2.5; + setVmMetricsStatus(`${visiblePoints.length} 个采样点 · ${stale ? "最近历史记录" : "最近采样"} ${formatMetricTime(latest)} · 每分钟自动刷新${stale ? "(当前无新数据)" : ""}`, stale); +} + +function resourceValue(item, kind) { + if (typeof item === "string") return item; + if (item && typeof item === "object") return String(kind === "iso" ? (item.path || item.name || "") : (item.name || item.id || "")); + return ""; +} + +function resourceLabel(item, kind) { + if (typeof item === "string") return kind === "iso" ? item.split("/").pop() : item; + if (item && typeof item === "object") return String(item.label || item.name || item.path || item.id || ""); + return ""; +} + +function fillSelect(id, items, kind) { + const select = byId(id); + const previous = select.value; + select.replaceChildren(); + const placeholder = document.createElement("option"); + placeholder.value = ""; + placeholder.textContent = items.length ? (kind === "iso" ? "选择安装镜像" : "选择虚拟网络或网桥") : (kind === "iso" ? "没有可用 ISO 镜像" : "没有可用虚拟网络或网桥"); + select.append(placeholder); + for (const item of items) { + const value = resourceValue(item, kind); + if (!value) continue; + const option = document.createElement("option"); + option.value = value; + option.textContent = resourceLabel(item, kind); + select.append(option); + } + if (previous && Array.from(select.options).some((option) => option.value === previous)) select.value = previous; + select.disabled = select.options.length <= 1; +} + +async function loadResources() { + const epoch = state.sessionEpoch; + try { + const result = await api("/api/v1/resources"); + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + state.resources = result || {}; + fillSelect("vm-network", Array.isArray(result?.networks) ? result.networks : [], "network"); + fillSelect("vm-iso", Array.isArray(result?.isos) ? result.isos : [], "iso"); + updateCreateSource(); + showResourceWarning(""); + } catch (error) { + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + state.resources = null; + fillSelect("vm-network", [], "network"); + fillSelect("vm-iso", [], "iso"); + updateCreateSource(); + showResourceWarning(state.admin + ? `宿主机资源尚未就绪:${error.message}。请检查存储池和网络或网桥设置。` + : `宿主机资源尚未就绪:${error.message}。请联系管理员检查宿主机。`); + throw error; + } +} + +const TEMPLATE_FAMILY_NAMES = { + almalinux: "AlmaLinux", + debian: "Debian", + centos: "CentOS", + centosstream: "CentOS", + ubuntu: "Ubuntu", +}; + +const TEMPLATE_ICON_PATHS = { + AlmaLinux: "/static/almalinux-icon.svg", + Debian: "/static/debian-icon.svg", + CentOS: "/static/centos-icon.svg", + Ubuntu: "/static/ubuntu-icon.svg", +}; + +function templateSystem(item) { + const id = String(item?.id || ""); + const familyKey = String(item?.os_family || "").trim().toLowerCase().replace(/[\s_-]+/g, ""); + const namedFamily = Object.prototype.hasOwnProperty.call(TEMPLATE_FAMILY_NAMES, familyKey) + ? TEMPLATE_FAMILY_NAMES[familyKey] : ""; + const family = namedFamily + || (/^alma(?:9|10)-/.test(id) ? "AlmaLinux" : "其他系统"); + const oldVersion = /^alma(9|10)-/.exec(id)?.[1] || ""; + const version = /^[0-9]+$/.test(String(item?.os_version || "")) + ? String(item.os_version) : oldVersion; + return { family, version }; +} + +function templateIcon(family, className) { + const logoPath = TEMPLATE_ICON_PATHS[family]; + const icon = makeElement("span", `${className}${logoPath ? " system" : ""}`); + icon.setAttribute("aria-hidden", "true"); + if (logoPath) { + const logo = makeElement("img", "template-system-logo"); + logo.src = logoPath; + logo.alt = ""; + icon.append(logo); + } else { + icon.textContent = "◈"; + } + return icon; +} + +function renderTemplateCatalog(inputId) { + const input = byId(inputId); + const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog"); + const opened = new Set(Array.from(container.querySelectorAll("details[open]"), (detail) => detail.dataset.family)); + const groups = new Map(); + for (const item of state.templates) { + if (!item?.id) continue; + const { family, version } = templateSystem(item); + if (!groups.has(family)) groups.set(family, []); + groups.get(family).push({ item, version }); + } + if (!groups.size) { + input.value = ""; + container.replaceChildren(makeElement("p", "template-catalog-empty", state.admin + ? "暂无云镜像,请先到“云镜像模板”页面导入。" + : "暂无可用云镜像,请联系管理员导入模板。")); + return; + } + if (!state.templates.some((item) => String(item.id) === input.value)) input.value = ""; + const cards = []; + for (const [family, entries] of groups) { + entries.sort((a, b) => Number(b.version || 0) - Number(a.version || 0) + || String(a.item.name || "").localeCompare(String(b.item.name || ""), "zh-CN")); + const card = makeElement("details", "template-family-card"); + card.dataset.family = family; + card.open = opened.has(family) || entries.some(({ item }) => String(item.id) === input.value); + const summary = makeElement("summary", "template-family-summary"); + const icon = templateIcon(family, "template-family-icon"); + summary.append(icon, makeElement("strong", "", family), makeElement("span", "template-family-arrow", "⌄")); + const versions = makeElement("div", "template-versions"); + versions.setAttribute("role", "group"); + versions.setAttribute("aria-label", `${family} 可用版本`); + for (const { item } of entries) { + const id = String(item.id); + const name = String(item.name || id); + const option = makeElement("button", "template-version-option"); + option.type = "button"; + option.dataset.templateId = id; + option.setAttribute("aria-pressed", String(input.value === id)); + option.setAttribute("aria-label", `选择模板 ${name}`); + option.append(makeElement("strong", "", name)); + option.addEventListener("click", () => { + input.value = id; + container.querySelectorAll(".template-version-option").forEach((button) => { + button.setAttribute("aria-pressed", String(button.dataset.templateId === id)); + }); + if (inputId === "vm-template") showError("create-error", ""); + else showError("reinstall-error", ""); + }); + versions.append(option); + } + card.append(summary, versions); + cards.push(card); + } + container.replaceChildren(...cards); +} + +function renderTemplateAdminList() { + const list = byId("template-admin-list"); + list.replaceChildren(); + if (!state.admin) return; + if (!state.templates.length) { + list.append(makeElement("p", "muted", "当前宿主机还没有导入云镜像模板。")); + return; + } + for (const item of state.templates) { + const id = String(item?.id || ""); + if (!id) continue; + const { family, version } = templateSystem(item); + const row = makeElement("form", "template-admin-row"); + const heading = makeElement("div", "template-admin-row-heading"); + const icon = templateIcon(family, "template-admin-icon"); + heading.append(icon, makeElement("strong", "", `${family}${version ? ` ${version}` : ""}`)); + const label = makeElement("label", "", "模板名称"); + const name = makeElement("input", ""); + name.type = "text"; + name.required = true; + name.maxLength = 64; + name.value = String(item.name || ""); + name.setAttribute("autocomplete", "off"); + name.id = `template-admin-name-${id}`; + label.htmlFor = name.id; + const button = makeElement("button", "button button-outline small", "保存名称"); + button.type = "submit"; + const error = makeElement("p", "form-error"); + error.hidden = true; + error.setAttribute("role", "alert"); + row.addEventListener("submit", async (event) => { + event.preventDefault(); + const requested = name.value.trim(); + error.hidden = true; + if (!requested || requested.length > 64) { + error.textContent = "模板名称应为 1 至 64 个字符。"; + error.hidden = false; + return; + } + if (requested === item.name) return; + setButtonBusy(button, true, "正在保存…"); + try { + await api(`/api/v1/vm-templates/${encodeURIComponent(id)}`, { method: "PATCH", body: { name: requested } }); + await loadTemplates(); + toast("模板名称已更新。", "success"); + } catch (caught) { + error.textContent = caught.message; + error.hidden = false; + } finally { + if (button.isConnected) setButtonBusy(button, false); + } + }); + row.append(heading, label, name, button, error); + list.append(row); + } +} + +function fillTemplateViews(items, preferredId = "") { + state.templates = items.filter((item) => item && typeof item.id === "string"); + if (preferredId && state.templates.some((item) => item.id === preferredId)) byId("vm-template").value = preferredId; + renderTemplateCatalog("vm-template"); + renderTemplateCatalog("reinstall-template"); + renderTemplateAdminList(); + updateCreateSource(); +} + +async function loadTemplates(preferredId = "") { + if (state.templateLoad) await state.templateLoad; + const epoch = state.sessionEpoch; + const request = api("/api/v1/vm-templates"); + state.templateLoad = request; + try { + const result = await request; + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + fillTemplateViews(Array.isArray(result?.templates) ? result.templates : [], preferredId); + } finally { + if (state.templateLoad === request) state.templateLoad = null; + } +} + +function showTemplateImportStatus(message) { + const element = byId("template-import-status"); + element.textContent = message; + element.hidden = !message; +} + +async function waitForTemplateImport(jobId) { + for (let attempt = 0; attempt < 360; attempt += 1) { + await new Promise((resolve) => window.setTimeout(resolve, 5000)); + const job = await api(`/api/v1/vm-templates/import-jobs/${encodeURIComponent(jobId)}`); + if (job?.status === "completed") return job; + if (job?.status === "failed") { + state.templateImportJobId = null; + throw new Error(job.error || "模板导入失败,请核对下载地址和 SHA-256 校验值。"); + } + if (job?.status !== "running") throw new Error("模板导入状态未知,请稍后重新查看。"); + if (attempt % 6 === 5) { + const seconds = (attempt + 1) * 5; + showTemplateImportStatus(`宿主机正在后台导入镜像,已等待约 ${seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分钟`}。离开页面不会取消任务。`); + } + } + throw new Error("模板仍在后台导入。稍后返回“云镜像模板”页面查看导入状态。"); +} + +function selectedCreateSource() { + return document.querySelector('input[name="source"]:checked')?.value || "iso"; +} + +function configuredPublicPool() { + if (state.resources && Object.prototype.hasOwnProperty.call(state.resources, "public_pool_cidr")) { + return String(state.resources.public_pool_cidr || "").trim(); + } + return String(state.hostConfig?.public_pool_cidr || "").trim(); +} + +function updateCreateAuthMode() { + const cloud = selectedCreateSource() === "cloud"; + const password = byId("vm-root-password"); + password.disabled = !cloud; + updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); +} + +function manualRootPasswordIssue(value) { + if (!value) return ""; + const missing = []; + const characters = Array.from(value); + if (characters.length < 12) missing.push("至少 12 个字符"); + if (characters.length > 128) missing.push("不超过 128 个字符"); + if (!/[A-Z]/.test(value)) missing.push("大写字母"); + if (!/[a-z]/.test(value)) missing.push("小写字母"); + if (!/[^\p{L}\p{N}\s]/u.test(value)) missing.push("符号"); + if (characters.some((character) => character !== " " && /[\p{C}\p{Z}]/u.test(character))) missing.push("仅使用可打印字符"); + return missing.length ? `自行设置的初始 root 密码还需:${missing.join("、")}。` : ""; +} + +function updateRootPasswordHint(inputId, hintId) { + const value = byId(inputId).value; + const hint = byId(hintId); + const issue = manualRootPasswordIssue(value); + const creatingVm = inputId === "vm-root-password"; + const keySelected = !creatingVm && Boolean(selectedSshKeyId("reinstall-ssh-key-cards")); + hint.classList.toggle("root-password-hint-error", !!issue); + hint.classList.toggle("root-password-hint-success", !!value && !issue); + hint.textContent = issue || (value + ? "密码符合要求,可与 SSH 公钥同时使用。" + : `${creatingVm ? "留空时自动生成强密码,即使选择了 SSH 公钥" : keySelected ? "留空时仅允许 SSH 公钥登录,不生成密码" : "不选公钥且留空时自动生成强密码"};自行设置需至少 12 个字符,包含大写字母、小写字母和符号。`); +} + +function updateCreateSource() { + const cloud = selectedCreateSource() === "cloud"; + const publicPool = configuredPublicPool(); + const guestPrefix = state.resources?.public_vm_prefix + ?? state.hostConfig?.public_vm_prefix ?? parsePublicPool(publicPool)?.prefix; + const automaticPublicIp = cloud && Boolean(publicPool); + byId("vm-iso-field").hidden = cloud; + byId("vm-template-field").hidden = !cloud; + byId("vm-cloud-fields").hidden = !cloud; + byId("create-iso-tip").hidden = cloud; + byId("create-cloud-tip").hidden = !cloud; + byId("vm-auto-public-pool").hidden = !automaticPublicIp; + text("vm-auto-public-pool-description", publicPool + ? `创建时仅从 ${publicPool} 中选择未使用的公网 IP${guestPrefix ? `,虚拟机网卡使用 /${guestPrefix}` : ""},并自动配置宿主机保存的网关和 DNS。` + : "创建时将从宿主机地址池中选择未使用的 IP,并自动写入网关和 DNS。"); + byId("vm-manual-public-network").hidden = automaticPublicIp; + + const iso = byId("vm-iso"); + iso.required = !cloud; + iso.disabled = cloud || iso.options.length <= 1; + const template = byId("vm-template"); + template.disabled = !cloud; + byId("vm-guest-ssh-key-cards").hidden = !cloud; + ["vm-public-ip-cidr", "vm-gateway", "vm-dns"].forEach((id) => { + const input = byId(id); + input.required = cloud && !automaticPublicIp; + input.disabled = !cloud || automaticPublicIp; + }); + updateCreateAuthMode(); + + const network = byId("vm-network"); + for (const option of network.options) { + option.disabled = cloud && !!option.value && !option.value.startsWith("bridge:"); + } + if (cloud && network.value && !network.value.startsWith("bridge:")) network.value = ""; + if (cloud && !network.value) { + const bridge = Array.from(network.options).find((option) => option.value.startsWith("bridge:")); + if (bridge) network.value = bridge.value; + } +} + +function openModal(id) { + if (state.activeModal) closeModal(); + state.lastFocus = document.activeElement; + state.activeModal = byId(id); + state.activeModal.hidden = false; + document.body.style.overflow = "hidden"; + const focusTarget = state.activeModal.querySelector("input:not(:disabled),button:not(:disabled)"); + window.requestAnimationFrame(() => focusTarget?.focus()); +} + +function closeModal() { + if (!state.activeModal) return; + const returnFocus = state.lastFocus; + if (state.activeModal.id === "console-modal") disconnectConsole(); + state.activeModal.hidden = true; + state.activeModal = null; + state.deleteTarget = null; + state.confirmTarget = null; + document.body.style.overflow = ""; + if (returnFocus?.isConnected && returnFocus.getClientRects().length && !returnFocus.disabled) { + returnFocus.focus(); + } else if (!byId("vm-workspace").hidden && !byId("vm-detail-view").hidden) { + const action = returnFocus?.dataset?.vmAction; + const replacement = action ? Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) + .find((button) => button.dataset.vmAction === action && !button.disabled) : null; + (replacement || byId("vm-detail-name")).focus(); + } +} + +function openCreate() { + if (!state.admin && (!state.approved || !state.hostReady)) return; + if (!showVmWorkspace()) return; + resetCreatePage(); + fillSshKeyCards(state.sshKeys); + clearSshKeyPicker("vm-guest-ssh-key-cards"); + showError("create-error", ""); + updateCreateSource(); + showVmSubpage("create"); + if (!state.resources) { + void loadResources().catch((error) => showError("create-error", `无法加载宿主机资源:${error.message}`)); + } + void loadSshKeys().catch((error) => showError("create-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`)); +} + +function openDelete(vm) { + state.deleteTarget = vm; + text("delete-vm-name", vm.name || vm.uuid || "此虚拟机"); + byId("delete-disks").checked = false; + showError("delete-error", ""); + openModal("delete-modal"); + state.deleteTarget = vm; +} + +function renderRescueState(result) { + state.rescueActive = result?.active === true; + state.rescueStaged = result?.staged === true; + state.rescuePowerState = String(result?.power_state || "unknown"); + state.rescueCanExit = result?.can_exit === true; + const templateName = String(result?.template_name || ""); + const rescueIsStopped = stateCategory(state.rescuePowerState) === "stopped"; + text("rescue-status", state.rescueActive + ? `已按救援配置开机${templateName ? ` · ${templateName}` : ""}。请通过 VNC 确认实际进入救援系统;退出救援后将从原系统盘启动。` + : state.rescueStaged + ? `救援 ISO 已预挂载${templateName ? ` · ${templateName}` : ""}。${rescueIsStopped ? "虚拟机已关机,可点击“从救援 ISO 开机”。" : "正常关机未完成时,可确认风险后点击“强制重启进入救援”;也可在详情页手动“强制断电”再“开机”。"}普通“强制重置”不保证读取新启动配置。` + : "当前未处于救援模式。加载救援 ISO 不会删除原系统盘。" ); + const pending = state.rescueInProgress; + byId("rescue-submit").hidden = state.rescueActive || state.rescueStaged; + byId("rescue-force-start").hidden = !state.rescueStaged; + text("rescue-force-start", rescueIsStopped ? "从救援 ISO 开机" : "强制重启进入救援"); + byId("rescue-exit").hidden = !state.rescueActive && !state.rescueStaged; + text("rescue-exit", state.rescueStaged ? "取消救援并卸载 ISO" : "退出救援并重启原系统"); + byId("rescue-submit").disabled = pending; + byId("rescue-force-start").disabled = pending || !state.rescueCanExit; + byId("rescue-exit").disabled = pending || !state.rescueCanExit; + byId("rescue-template-cards").hidden = state.rescueActive || state.rescueStaged; + byId("rescue-template-label").hidden = state.rescueActive || state.rescueStaged; + byId("rescue-template-cards").querySelectorAll("button").forEach((button) => { button.disabled = pending; }); +} + +async function loadVmRescueState(uuid) { + const result = await api(`/api/v1/vms/${encodeURIComponent(uuid)}/rescue`); + if (state.rescueTarget?.uuid !== uuid || byId("rescue-view").hidden) return result; + renderRescueState(result); + if ((state.rescueActive || state.rescueStaged) && !state.rescueCanExit) { + showError("rescue-error", "救援配置缺少可用的原系统恢复记录;请联系管理员检查,面板不会盲目卸载。" ); + } + return result; +} + +async function pollVmRescueJob(jobId, uuid, token) { + for (let attempt = 0; attempt < 720 && token === state.rescuePollToken; attempt += 1) { + try { + const job = await api(`/api/v1/rescue-jobs/${encodeURIComponent(jobId)}`); + if (token !== state.rescuePollToken || state.rescueTarget?.uuid !== uuid) return; + if (job?.status === "completed") { + state.rescueInProgress = false; + state.rescueJobId = null; + try { sessionStorage.removeItem(rescueJobStorageKey(uuid)); } catch { /* Ignore private browsing limits. */ } + const warnings = []; + try { + await loadVmRescueState(uuid); + } catch (error) { + warnings.push(`救援任务已完成,但状态刷新失败:${error.message}。请刷新页面核对虚拟机。`); + } + if ((state.rescueActive || state.rescueStaged) && !state.rescueCanExit) warnings.push("缺少原系统恢复记录,请联系管理员检查,勿手动切换启动配置。" ); + if (job.pending_manual_restart === true) warnings.unshift("正常关机失败或超时,救援 ISO 已预挂载但尚未进入救援系统。可在本页确认风险后点“强制重启进入救援”(强制断电再冷启动,可能丢失未保存数据);也可返回详情页手动“强制断电”后点“开机”。不要使用普通“强制重置”。"); + if (typeof job.warning === "string" && job.warning.trim()) warnings.push(job.warning.trim()); + showError("rescue-error", warnings.join(";")); + void loadVMs(true); + toast(job.pending_manual_restart === true + ? "救援 ISO 已预挂载,但正常关机未完成;可在本页确认后强制重启进入救援。" + : warnings.length ? "救援任务已完成,但有警告;请查看页面提示与 VNC 控制台。" : "救援操作已完成,请检查虚拟机状态和控制台。", warnings.length ? "info" : "success"); + return; + } + if (job?.status === "failed") { + state.rescueInProgress = false; + const failureMessage = job.error || "救援任务失败。请检查虚拟机当前电源状态和宿主机日志;面板未强制断电。"; + const shutdownFailed = /正常关机超时|无法请求虚拟机正常关机/.test(failureMessage); + let current = null; + try { current = await loadVmRescueState(uuid); } catch { /* Keep the job ID until state can be verified. */ } + const hasRecoveryInstructions = /详情页手动“强制断电”|救援系统的 VNC 控制台手动关机/.test(failureMessage); + const recoveryAdvice = current?.staged === true && job.operation === "enter" + ? "救援 ISO 已预挂载,但正常关机未完成。可在本页确认风险后点击“强制重启进入救援”;也可返回详情页手动“强制断电”(可能丢失未保存数据),确认“已关机”后点“开机”。不要使用普通“强制重置”:它不保证读取新启动配置。面板不会自动强制断电。" + : hasRecoveryInstructions ? "" : shutdownFailed && job.operation === "enter" + ? "尚未确认救援 ISO 已预挂载,请先核查救援状态;不要直接强制重启。预挂载成功后,才能通过“强制断电”再“开机”进入救援。" + : shutdownFailed && job.operation === "exit" + ? "退出救援时正常关机未完成。详情页强制操作在救援模式下不可用;可通过救援系统的 VNC 控制台手动关机,待显示“已关机”后重试退出救援。面板不会自动强制断电。" + : "请核查虚拟机当前状态和救援失败原因;面板不会自动强制断电或重启。"; + const recoveryWarning = (current?.active || current?.staged) && !current?.can_exit + ? "缺少原系统恢复记录,请联系管理员检查。" : ""; + showError("rescue-error", [failureMessage, recoveryAdvice, recoveryWarning].filter(Boolean).join(";")); + if (current && (current.can_exit === true || (!current.active && !current.status))) { + state.rescueJobId = null; + try { sessionStorage.removeItem(rescueJobStorageKey(uuid)); } catch { /* Ignore private browsing limits. */ } + } + return; + } + if (job?.status !== "queued" && job?.status !== "running") throw new Error("救援任务状态未知,请稍后重新打开此页面查询。"); + state.rescueInProgress = true; + text("rescue-status", job.phase || (job.status === "queued" ? "救援任务排队中…" : "正在预挂载救援 ISO 并等待正常关机…")); + byId("rescue-submit").disabled = true; + byId("rescue-force-start").disabled = true; + byId("rescue-exit").disabled = true; + byId("rescue-template-cards").querySelectorAll("button").forEach((button) => { button.disabled = true; }); + } catch (error) { + if (token !== state.rescuePollToken) return; + state.rescueInProgress = false; + showError("rescue-error", `暂时无法查询救援任务:${error.message}。请勿重复提交,稍后重新打开页面查看状态。`); + return; + } + await new Promise((resolve) => window.setTimeout(resolve, 5000)); + } + if (token === state.rescuePollToken) { + showError("rescue-error", "尚未确认救援任务完成。请稍后重新打开页面查询,不要重复提交。"); + } +} + +async function openRescue(vm) { + const uuid = String(vm.uuid || ""); + if (!uuid) return; + state.rescuePollToken += 1; + state.rescueTarget = vm; + state.rescueActive = false; + state.rescueStaged = false; + state.rescuePowerState = "unknown"; + state.rescueCanExit = false; + state.rescueInProgress = false; + state.rescueJobId = null; + byId("rescue-form").reset(); + byId("rescue-template-id").value = ""; + text("rescue-subtitle", `${vm.name || uuid} · 选择救援 ISO 并确认切换启动。`); + text("rescue-confirm-hint", `请准确输入“${vm.name || ""}”。面板会先预挂载救援 ISO,再请求运行中的虚拟机正常关机并从救援 ISO 开机;停机虚拟机将直接从救援 ISO 开机。`); + byId("rescue-confirm-name").placeholder = vm.name || "请输入完整的虚拟机名称"; + text("rescue-status", "正在检查虚拟机状态…"); + byId("rescue-submit").disabled = true; + byId("rescue-force-start").disabled = true; + byId("rescue-exit").disabled = true; + showError("rescue-error", ""); + showVmSubpage("rescue"); + const [templates, current] = await Promise.allSettled([loadRescueTemplates(), loadVmRescueState(uuid)]); + if (state.rescueTarget?.uuid !== uuid || byId("rescue-view").hidden) return; + if (templates.status === "rejected") showError("rescue-error", `无法读取救援模版:${templates.reason.message}`); + if (current.status === "rejected") { + showError("rescue-error", `无法读取虚拟机救援状态:${current.reason.message}`); + text("rescue-status", "状态未知;为避免误操作,暂时不能提交救援。"); + return; + } + const rescueState = current.value; + const pendingJobId = storedRescueJob(uuid) || (["queued", "running"].includes(rescueState?.status) + ? String(rescueState.job_id || "") : ""); + if (pendingJobId) { + state.rescueJobId = pendingJobId; + state.rescueInProgress = true; + void pollVmRescueJob(pendingJobId, uuid, ++state.rescuePollToken); + } +} + +function leaveRescuePage() { + const uuid = String(state.rescueTarget?.uuid || ""); + if (!showVmWorkspace()) return; + if (uuid && state.vms.some((item) => String(item.uuid || "") === uuid)) openVmDetail(uuid); +} + +function openReinstall(vm) { + if (readSavedReinstallJob()) { + resumeReinstallJob(); + toast("此标签页已有重装任务,已恢复任务状态;请不要重复提交。", "info"); + return; + } + resetReinstallPage(); + fillSshKeyCards(state.sshKeys); + clearSshKeyPicker("reinstall-ssh-key-cards"); + updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); + byId("reinstall-fields").hidden = false; + byId("reinstall-progress").hidden = true; + byId("reinstall-result").hidden = true; + byId("reinstall-password-box").hidden = true; + byId("reinstall-generated-password").textContent = ""; + byId("reinstall-result-warning").hidden = true; + byId("reinstall-cancel").hidden = false; + byId("reinstall-submit").hidden = false; + byId("reinstall-forget").hidden = true; + byId("reinstall-retry").hidden = true; + byId("reinstall-done").hidden = true; + text("reinstall-done", "完成"); + byId("reinstall-back").disabled = false; + showError("reinstall-error", ""); + text("reinstall-subtitle", `${vm.name || vm.uuid} · 保留公网网络参数,重新创建系统盘。`); + text("reinstall-public-ip", String(vm.public_ip_cidr || "未知")); + text("reinstall-confirm-hint", `请准确输入“${vm.name || ""}”;这也是防止选错虚拟机的最后一道确认。`); + byId("reinstall-confirm-name").placeholder = vm.name || "请输入完整的虚拟机名称"; + state.reinstallTarget = vm; + showVmSubpage("reinstall"); + void loadTemplates().catch((error) => showError("reinstall-error", `无法加载重装模板:${error.message}`)); + void loadSshKeys().catch((error) => showError("reinstall-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`)); +} + +function leaveReinstallPage() { + if (!canLeaveReinstallPage()) return; + const uuid = String(state.reinstallTarget?.uuid || ""); + if (!showVmWorkspace()) return; + if (uuid && state.vms.some((vm) => String(vm.uuid || "") === uuid)) openVmDetail(uuid); + else byId("vm-list-title").focus(); +} + +function resumeReinstallJob() { + const saved = readSavedReinstallJob(); + if (!saved) return; + if (state.reinstallJobId === saved.job_id && (state.reinstallInProgress || state.reinstallPasswordPendingAck)) { + showVmSubpage("reinstall"); + return; + } + byId("reinstall-form").reset(); + byId("reinstall-fields").hidden = true; + byId("reinstall-result").hidden = true; + byId("reinstall-progress").hidden = false; + byId("reinstall-cancel").hidden = true; + byId("reinstall-submit").hidden = true; + byId("reinstall-forget").hidden = true; + byId("reinstall-retry").hidden = true; + byId("reinstall-done").hidden = true; + byId("reinstall-generated-password").textContent = ""; + byId("reinstall-password-box").hidden = true; + showError("reinstall-error", ""); + text("reinstall-subtitle", "正在恢复此标签页中尚未确认的重装任务。"); + text("reinstall-phase", "正在查询已有重装任务…"); + state.reinstallTarget = null; + state.reinstallJobId = saved.job_id; + state.reinstallExpectGeneratedPassword = Boolean(saved.expect_generated_password); + state.reinstallPasswordPendingAck = false; + state.reinstallInProgress = true; + byId("reinstall-back").disabled = true; + showVmSubpage("reinstall"); + const token = ++state.reinstallPollToken; + void pollReinstallJob(saved.job_id, token); +} + +function reinstallPhaseLabel(phase) { + const labels = { + queued: "等待执行…", + validating: "检查虚拟机、模板和原系统盘…", + shutting_down: "正在请求虚拟机正常关机…", + waiting_for_shutdown: "等待虚拟机完成正常关机…", + preparing: "正在准备新的系统盘和 cloud-init 配置…", + cloning: "正在复制云镜像模板到新系统盘…", + defining: "正在切换虚拟机系统盘…", + starting: "正在启动新系统…", + cleaning_up: "libvirt/QEMU 已报告启动,正在删除旧系统盘…", + }; + return labels[phase] || (typeof phase === "string" && phase.trim() ? phase : "正在执行重装任务…"); +} + +function showReinstallResult(success, message, job = {}, terminal = true) { + state.reinstallInProgress = false; + const password = success && typeof job.generated_password === "string" ? job.generated_password : ""; + state.reinstallPasswordPendingAck = Boolean(password); + if (terminal && !state.reinstallPasswordPendingAck) { + state.reinstallJobId = null; + clearSavedReinstallJob(); + } + byId("reinstall-fields").hidden = true; + byId("reinstall-progress").hidden = true; + byId("reinstall-result").hidden = false; + byId("reinstall-cancel").hidden = true; + byId("reinstall-submit").hidden = true; + byId("reinstall-forget").hidden = true; + byId("reinstall-retry").hidden = terminal; + byId("reinstall-done").hidden = false; + text("reinstall-done", state.reinstallPasswordPendingAck ? "已保存密码,完成" : "完成"); + byId("reinstall-back").disabled = state.reinstallPasswordPendingAck; + text("reinstall-result-title", success ? "重装任务已完成" : "重装任务未完成"); + text("reinstall-result-message", message); + byId("reinstall-result").classList.toggle("failed", !success); + byId("reinstall-result").classList.remove("unknown"); + byId("reinstall-generated-password").textContent = password; + byId("reinstall-password-box").hidden = !password; + const warnings = []; + if (typeof job.warning === "string" && job.warning) warnings.push(job.warning); + if (success && state.reinstallExpectGeneratedPassword && !password) { + warnings.push("未收到自动生成的 root 密码,请通过虚拟机控制台恢复 root 登录,并检查面板日志。"); + } + const warning = warnings.join(" "); + text("reinstall-result-warning", warning); + byId("reinstall-result-warning").hidden = !warning; + showError("reinstall-error", ""); +} + +function showReinstallUnknown(message) { + showReinstallResult(false, message, {}, false); + text("reinstall-result-title", "重装任务状态未明"); + byId("reinstall-result").classList.remove("failed"); + byId("reinstall-result").classList.add("unknown"); + byId("reinstall-done").hidden = true; + byId("reinstall-forget").hidden = false; +} + +async function pollReinstallJob(jobId, token) { + let consecutiveErrors = 0; + for (let attempt = 0; attempt < 600; attempt += 1) { + if (state.reinstallPollToken !== token) return; + let job; + try { + job = await api(`/api/v1/reinstall-jobs/${encodeURIComponent(jobId)}`, { csrf: true }); + consecutiveErrors = 0; + } catch (error) { + if (state.reinstallPollToken !== token) return; + if (error.status === 404) { + showReinstallUnknown("面板找不到此重装任务。面板进程可能已重启,内存中的任务和未确认密码可能已丢失。请检查虚拟机、旧盘和新盘状态,切勿直接再次重装;如有必要可在控制台恢复 root 登录。"); + return; + } + consecutiveErrors += 1; + text("reinstall-phase", `暂时无法读取任务进度(第 ${consecutiveErrors} 次):${error.message}。面板仍会继续查询。`); + } + if (state.reinstallPollToken !== token) return; + if (job) { + if (job.status === "succeeded" || job.status === "completed") { + showReinstallResult(true, "libvirt/QEMU 已报告虚拟机从新系统盘启动,但尚不能证明客户机系统、网络或 SSH 正常。请通过控制台及 SSH 验证。公网网络参数沿用原配置。", job); + void loadVMs(true); + return; + } + if (job.status === "failed") { + showReinstallResult(false, String(job.error || "重装失败,请检查宿主机状态后再决定是否重试。"), job); + void loadVMs(true); + return; + } + text("reinstall-phase", reinstallPhaseLabel(job.phase || job.status)); + } + await new Promise((resolve) => window.setTimeout(resolve, 3000)); + } + if (state.reinstallPollToken === token) { + showReinstallUnknown("连续查询约 30 分钟仍未取得最终状态。任务可能仍在面板进程中运行;请点击“重新查询任务”,不要重新提交重装。若面板进程已重启,请先检查虚拟机、旧盘和新盘状态。"); + } +} + +function openConfirm(vm, action) { + const label = action === "poweroff" ? "强制断电" : "强制重置"; + text("confirm-title", label); + text("confirm-message", action === "poweroff" && vm.rescue_staged === true + ? `救援 ISO 已预挂载。确定强制断电 ${vm.name || vm.uuid} 吗?这可能丢失未保存的数据。确认虚拟机已关机后,请回详情页点“开机”进入救援系统;不要使用“强制重置”。` + : `确定对 ${vm.name || vm.uuid} 执行“${label}”吗?这可能导致虚拟机内未保存的数据丢失。`); + text("confirm-submit", label); + showError("confirm-error", ""); + openModal("confirm-modal"); + state.confirmTarget = { vm, action }; +} + +async function runAction(vm, action, button) { + const label = { start: "开机", shutdown: "关机", reboot: "重启", poweroff: "强制断电", reset: "强制重置" }[action] || action; + const focusAction = button?.dataset.vmAction || null; + if (state.vmActionInFlight === vm.uuid) return false; + state.vmActionInFlight = vm.uuid; + if (button) setButtonBusy(button, true); + if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh(); + try { + await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/actions`, { method: "POST", body: { action } }); + toast(vm.rescue_staged === true && action === "poweroff" + ? "已发送强制断电指令。确认状态为已关机后,请点“开机”进入救援系统。" + : vm.rescue_staged === true && action === "start" + ? "已发送开机指令,请通过 VNC 控制台确认已进入救援系统。" + : `已向 ${vm.name || vm.uuid} 发送${label}指令。`, "success"); + await loadVMs(true); + window.setTimeout(() => void loadVMs(true), 1200); + return true; + } catch (error) { + toast(`${label}失败:${error.message}`, "error"); + return false; + } finally { + state.vmActionInFlight = null; + if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh(); + if (button?.isConnected) setButtonBusy(button, false); + if (focusAction && !state.activeModal && state.selectedVmId === vm.uuid && !byId("vm-detail-view").hidden) { + const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) + .find((item) => item.dataset.vmAction === focusAction && !item.disabled); + (replacement || byId("vm-detail-name")).focus(); + } + } +} + +function disconnectConsole() { + state.consoleToken += 1; + const rfb = state.rfb; + state.rfb = null; + if (rfb) { + try { rfb.disconnect(); } catch { /* Already disconnected. */ } + } + const stage = byId("console-stage"); + const placeholder = byId("console-placeholder"); + stage.replaceChildren(placeholder); + placeholder.hidden = false; + byId("console-password-form").hidden = true; + byId("console-cad").disabled = true; +} + +async function openConsole(vm) { + openModal("console-modal"); + text("console-title", `${vm.name || vm.uuid} · 控制台`); + text("console-status", "正在连接…"); + const stage = byId("console-stage"); + const placeholder = byId("console-placeholder"); + placeholder.hidden = false; + const token = ++state.consoleToken; + try { + const { default: RFB } = await import("/vendor/novnc/core/rfb.js"); + if (token !== state.consoleToken) return; + const url = new URL(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/console`, location.href); + url.protocol = location.protocol === "https:" ? "wss:" : "ws:"; + const rfb = new RFB(stage, url.toString(), { shared: true }); + state.rfb = rfb; + placeholder.hidden = true; + rfb.scaleViewport = true; + rfb.resizeSession = false; + rfb.addEventListener("connect", () => { + if (state.rfb !== rfb) return; + text("console-status", "已连接"); + byId("console-cad").disabled = false; + }); + rfb.addEventListener("disconnect", (event) => { + if (state.rfb !== rfb) return; + text("console-status", event.detail?.clean ? "连接已关闭" : "连接已中断,请关闭后重试"); + byId("console-cad").disabled = true; + }); + rfb.addEventListener("credentialsrequired", () => { + if (state.rfb !== rfb) return; + byId("console-password-form").hidden = false; + byId("console-password").focus(); + text("console-status", "请输入 VNC 密码"); + }); + } catch (error) { + if (token !== state.consoleToken) return; + text("console-status", `连接失败:${error.message}`); + placeholder.hidden = false; + placeholder.lastElementChild.textContent = "控制台连接失败,请关闭后重试。"; + } +} + +byId("database-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("database-error", ""); + const button = byId("database-submit"); + const token = byId("database-token").value.trim(); + const body = { + host: byId("database-host").value.trim(), + port: Number(byId("database-port").value), + database: byId("database-name").value.trim(), + username: byId("database-username").value.trim(), + password: byId("database-password").value, + setup_token: token, + }; + setButtonBusy(button, true, "正在连接…"); + try { + requireSecureCredentialTransport(); + const result = await api("/api/v1/database/setup", { method: "POST", csrf: false, body }); + if (result?.configured !== true) throw new Error("无法确认数据库配置已保存,请刷新页面后检查状态。"); + byId("setup-token").value = token; + byId("database-password").value = ""; + byId("database-token").value = ""; + showSetup(); + } catch (error) { + showError("database-error", error.message); + } finally { + delete body.password; + delete body.setup_token; + byId("database-password").value = ""; + byId("database-token").value = ""; + setButtonBusy(button, false); + } +}); + +byId("setup-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("setup-error", ""); + const password = byId("setup-password").value; + if (password !== byId("setup-password-confirm").value) { + showError("setup-error", "两次输入的初始用户密码不一致。"); + return; + } + const button = byId("setup-submit"); + setButtonBusy(button, true, "正在创建…"); + try { + requireSecureCredentialTransport(); + const session = await api("/api/v1/setup/admin", { + method: "POST", csrf: false, + body: { + token: byId("setup-token").value.trim(), + username: byId("setup-username").value.trim(), + password, + }, + }); + if (!session?.authenticated || !session?.csrf_token) throw new Error("初始用户已创建,但未能登录。请刷新页面后使用邮箱登录。"); + byId("setup-token").value = ""; + byId("setup-password").value = ""; + byId("setup-password-confirm").value = ""; + await continueAfterLogin(session); + } catch (error) { + showError("setup-error", error.message); + } finally { + setButtonBusy(button, false); + } +}); + +byId("login-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("login-error", ""); + byId("login-success").hidden = true; + const button = byId("login-submit"); + setButtonBusy(button, true, "正在登录…"); + try { + requireSecureCredentialTransport(); + const session = await api("/api/v1/login", { + method: "POST", csrf: false, + body: { email: byId("login-email").value.trim(), password: byId("login-password").value }, + }); + if (!session?.authenticated) throw new Error("登录失败,请检查邮箱和密码。"); + byId("login-password").value = ""; + await continueAfterLogin(session); + } catch (error) { + showError("login-error", error.message); + } finally { + setButtonBusy(button, false); + } +}); + +byId("show-register-button").addEventListener("click", showRegister); +byId("show-login-button").addEventListener("click", () => { + showLogin(); + byId("login-email").focus(); +}); + +byId("register-code-send").addEventListener("click", async () => { + showError("register-error", ""); + const emailInput = byId("register-email"); + if (!emailInput.checkValidity()) { + showError("register-error", "请先填写有效的邮箱地址。"); + emailInput.focus(); + return; + } + const button = byId("register-code-send"); + setButtonBusy(button, true, "正在发送…"); + try { + requireSecureCredentialTransport(); + const result = await api("/api/v1/register/code", { method: "POST", csrf: false, body: { email: emailInput.value.trim() } }); + if (result?.sent !== true) throw new Error("面板未确认验证码已发送,请稍后重试。"); + text("register-code-status", "如邮箱可注册且邮件服务可用,验证码将发送至该邮箱。请检查收件箱和垃圾邮件。"); + byId("register-code-status").hidden = false; + } catch (error) { + showError("register-error", error.message); + } finally { + setButtonBusy(button, false); + } +}); + +byId("register-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("register-error", ""); + const password = byId("register-password").value; + if (password !== byId("register-password-confirm").value) { + showError("register-error", "两次输入的密码不一致。"); + return; + } + const button = byId("register-submit"); + setButtonBusy(button, true, "正在注册…"); + try { + requireSecureCredentialTransport(); + const username = byId("register-username").value.trim(); + const email = byId("register-email").value.trim(); + const result = await api("/api/v1/register", { method: "POST", csrf: false, body: { + username, + email, + password, + code: byId("register-code").value.trim(), + } }); + if (result?.registered !== true) throw new Error("面板未确认注册结果,请勿重复提交,稍后尝试登录。"); + byId("register-form").reset(); + showLogin(); + byId("login-email").value = email; + text("login-success", "邮箱已验证,注册成功。账号需等待管理员审核通过后才能创建虚拟机;你可以先登录查看审核状态。"); + byId("login-success").hidden = false; + } catch (error) { + showError("register-error", error.message); + } finally { + byId("register-password").value = ""; + byId("register-password-confirm").value = ""; + setButtonBusy(button, false); + } +}); + +byId("wait-refresh-button").addEventListener("click", async () => { + const button = byId("wait-refresh-button"); + setButtonBusy(button, true, "正在检查…"); + try { + const session = await api("/api/v1/session"); + if (!session?.authenticated) { showLogin(); return; } + await continueAfterLogin(session); + } catch (error) { + toast(`状态检查失败:${error.message}`, "error"); + } finally { + setButtonBusy(button, false); + } +}); +byId("wait-ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspace()); + +byId("smtp-settings-form").addEventListener("submit", async (event) => { + event.preventDefault(); + if (!state.admin) return; + showError("smtp-error", ""); + const button = byId("smtp-save-button"); + const body = { + host: byId("smtp-host").value.trim(), + port: Number(byId("smtp-port").value), + tls_mode: byId("smtp-tls-mode").value, + username: byId("smtp-username").value.trim(), + password: byId("smtp-password").value, + from_address: byId("smtp-from-address").value.trim(), + }; + setButtonBusy(button, true, "正在保存…"); + try { + requireSecureCredentialTransport(); + await api("/api/v1/smtp/settings", { method: "PUT", body }); + await loadSmtpSettings(); + toast("邮件设置已保存。", "success"); + } catch (error) { + showError("smtp-error", error.message); + } finally { + delete body.password; + byId("smtp-password").value = ""; + setButtonBusy(button, false); + } +}); + +async function logout(button) { + if (!canLeaveReinstallPage()) return; + setButtonBusy(button, true, "退出中…"); + try { + await api("/api/v1/logout", { method: "POST" }); + showLogin(); + } catch (error) { + toast(`退出失败:${error.message}`, "error"); + } finally { + setButtonBusy(button, false); + } +} + +byId("logout-button").addEventListener("click", () => void logout(byId("logout-button"))); +byId("wait-logout-button").addEventListener("click", () => void logout(byId("wait-logout-button"))); +byId("host-logout-button").addEventListener("click", () => void logout(byId("host-logout-button"))); +byId("unlock-logout-button").addEventListener("click", () => void logout(byId("unlock-logout-button"))); +function openHostSettings() { + if (!canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); + showHostView(state.hostConfig || { configured: true }); +} +byId("host-settings-button").addEventListener("click", openHostSettings); +byId("host-settings-mobile-button").addEventListener("click", openHostSettings); +byId("host-update-button").addEventListener("click", () => openUpdateFromGate("host")); +byId("unlock-update-button").addEventListener("click", () => openUpdateFromGate("unlock")); +byId("vm-navigation-button").addEventListener("click", leaveUpdateWorkspace); +byId("vm-navigation-mobile-button").addEventListener("click", leaveUpdateWorkspace); +byId("ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspace()); +byId("ssh-keys-mobile-button").addEventListener("click", () => void showSshKeysWorkspace()); +byId("template-settings-button").addEventListener("click", () => void showTemplateWorkspace()); +byId("template-settings-mobile-button").addEventListener("click", () => void showTemplateWorkspace()); +byId("rescue-templates-button").addEventListener("click", () => void showRescueTemplatesWorkspace()); +byId("rescue-templates-mobile-button").addEventListener("click", () => void showRescueTemplatesWorkspace()); +byId("update-settings-button").addEventListener("click", () => void showUpdateWorkspace()); +byId("update-settings-mobile-button").addEventListener("click", () => void showUpdateWorkspace()); +byId("smtp-settings-button").addEventListener("click", () => void showSmtpWorkspace()); +byId("smtp-settings-mobile-button").addEventListener("click", () => void showSmtpWorkspace()); +byId("smtp-back-button").addEventListener("click", showVmWorkspace); +byId("ssh-keys-back-button").addEventListener("click", returnFromSshKeysWorkspace); +byId("template-back-button").addEventListener("click", showVmWorkspace); +byId("rescue-templates-back").addEventListener("click", showVmWorkspace); +byId("update-back-button").addEventListener("click", leaveUpdateWorkspace); +byId("unlock-settings-button").addEventListener("click", openHostSettings); +byId("host-back-button").addEventListener("click", () => { + clearHostPrivateKey(); + if (state.hostConfig?.key_locked) showUnlockView(state.hostConfig); + else void showDashboard({ username: state.username, csrf_token: state.csrfToken }); +}); +byId("host-address").addEventListener("input", resetFingerprint); +byId("host-port").addEventListener("input", resetFingerprint); +for (const id of ["host-region", "host-storage-pool", "host-iso-pool", "host-rescue-iso-pool", "host-network", "host-public-pool-cidr", "host-public-gateway", "host-public-vm-prefix", "host-public-dns", "host-public-reserved"]) { + byId(id).addEventListener("input", markHostTestStale); +} +byId("host-public-pool-cidr").addEventListener("input", refreshPublicPoolPreview); +byId("host-private-key").addEventListener("input", () => { + if (state.uploadedPrivateKey) { + state.uploadedPrivateKey = ""; + byId("host-private-key-file").value = ""; + text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。"); + } + markHostTestStale(); +}); +byId("host-private-key-passphrase").addEventListener("input", markHostTestStale); +byId("host-scan-button").addEventListener("click", () => void scanHost()); +byId("host-test-button").addEventListener("click", () => void submitHost(false)); +byId("host-form").addEventListener("submit", (event) => { + event.preventDefault(); + void submitHost(true); +}); +byId("unlock-form").addEventListener("submit", (event) => { + event.preventDefault(); + void submitUnlock(); +}); +byId("host-private-key-file").addEventListener("change", async (event) => { + state.uploadedPrivateKey = ""; + const input = event.currentTarget; + const file = input.files?.[0]; + if (!file) { + text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。"); + return; + } + if (file.size > 64 * 1024) { + input.value = ""; + showError("host-error", "私钥文件超过 64 KiB,请检查是否选错文件。"); + return; + } + try { + const content = await file.text(); + if (input.files?.[0] !== file) return; + state.uploadedPrivateKey = content; + byId("host-private-key").value = ""; + text("host-key-file-label", `已选择 ${file.name};文件内容不会在页面回显。`); + showError("host-error", ""); + markHostTestStale(); + } catch { + input.value = ""; + showError("host-error", "无法读取所选私钥文件,请重试或粘贴私钥内容。"); + } +}); + +byId("update-settings-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("update-settings-error", ""); + const body = { repository_url: UPDATE_REPOSITORY_URL, branch: UPDATE_BRANCH }; + const accessToken = byId("update-access-token").value; + if (accessToken) body.access_token = accessToken; + if (!accessToken && !state.updateSettings?.token_configured) { + showError("update-settings-error", "请填写具有仓库读取权限的 Gitea 访问令牌。"); + return; + } + const button = byId("update-settings-submit"); + setButtonBusy(button, true, "正在保存…"); + try { + requireSecureCredentialTransport(); + const settings = await api("/api/v1/update/settings", { method: "PUT", body }); + state.updateSettings = { configured: Boolean(settings?.configured), token_configured: Boolean(settings?.token_configured) }; + state.updateCheck = null; + byId("update-check-button").disabled = !settings?.configured; + byId("update-apply-button").disabled = true; + byId("update-access-token").value = ""; + text("update-token-hint", "访问令牌已保存;留空则继续使用现有令牌。令牌不会在页面回显。"); + text("update-latest-version", "—"); + text("update-status", settings?.checkout_error || "访问令牌已保存。请点击“检查更新”。"); + toast("更新来源已保存。", "success"); + } catch (error) { + showError("update-settings-error", error.message); + } finally { + delete body.access_token; + byId("update-access-token").value = ""; + setButtonBusy(button, false); + } +}); + +byId("update-check-button").addEventListener("click", async () => { + showError("update-action-error", ""); + const button = byId("update-check-button"); + setButtonBusy(button, true, "正在检查…"); + byId("update-apply-button").disabled = true; + try { + const result = await api("/api/v1/update/check", { method: "POST" }); + state.updateCheck = result; + text("update-current-version", result?.current_version || "—"); + text("update-latest-version", result?.latest_version || "—"); + const available = result?.update_available === true; + byId("update-apply-button").disabled = !available || Boolean(state.updateJobId); + text("update-status", available ? "发现新版本。请先备份数据库和面板数据,再点击“一键更新”。" : "当前已是最新版本。"); + } catch (error) { + state.updateCheck = null; + showError("update-action-error", `检查更新失败:${error.message}`); + text("update-status", "未能确认仓库版本,请检查更新来源与令牌。"); + } finally { + setButtonBusy(button, false); + } +}); + +byId("update-apply-button").addEventListener("click", async () => { + if (!state.updateCheck?.update_available || state.updateJobId) return; + const expectedCurrent = String(state.updateCheck.current_version || ""); + const expectedRemote = String(state.updateCheck.latest_version || ""); + if (!expectedCurrent || !expectedRemote) { + showError("update-action-error", "缺少已检查的提交编号,请重新检查更新。"); + return; + } + if (!window.confirm(`即将把面板更新到已检查的提交 ${expectedRemote.slice(0, 12)}。如果仓库版本已变化,更新会停止并要求重新检查。过程可能重启服务。确认已备份数据库和面板数据,并且可以使用服务器控制台恢复后,再继续。确定执行吗?`)) return; + showError("update-action-error", ""); + const button = byId("update-apply-button"); + setButtonBusy(button, true, "正在提交…"); + byId("update-check-button").disabled = true; + try { + const started = await api("/api/v1/update/apply", { method: "POST", body: { + expected_current_commit: expectedCurrent, + expected_remote_commit: expectedRemote, + } }); + const jobId = String(started?.job_id || ""); + if (!jobId) throw new Error("未收到更新任务编号;请检查服务端状态,勿重复提交。"); + state.updateJobId = jobId; + text("update-status", "更新任务已提交,正在查询进度。服务可能短暂断开。"); + void pollUpdateJob(jobId, ++state.updatePollToken); + } catch (error) { + showError("update-action-error", `提交更新失败:${error.message}`); + byId("update-check-button").disabled = false; + } finally { + setButtonBusy(button, false); + byId("update-apply-button").disabled = true; + } +}); + +byId("refresh-button").addEventListener("click", () => void loadVMs()); +byId("vm-detail-refresh-button").addEventListener("click", () => { + void loadVMs(); + void loadVmMetrics(); +}); +byId("vm-detail-ip-copy").addEventListener("click", async () => { + const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId); + const ip = vm && vmIp(vm); + if (!ip || ip === "未获取") return; + try { + await copyText(ip); + toast("公网 IP 已复制。", "success"); + } catch (error) { + toast(error.message, "error"); + } +}); +byId("vm-detail-password-reveal").addEventListener("click", async () => { + const uuid = state.selectedVmId; + const vm = state.vms.find((item) => String(item.uuid || "") === uuid); + if (!uuid || !vm?.password_available || state.credentialBusy) return; + if (state.credentialVisible && state.credentialVmId === uuid) { + clearVmCredential(); + renderVmCredentialStatus(vm); + return; + } + state.credentialBusy = true; + renderVmCredentialStatus(vm); + try { + const password = await readVmCredential(uuid); + if (!password) return; + state.credentialVmId = uuid; + state.credentialPassword = password; + state.credentialVisible = true; + state.credentialHideTimer = window.setTimeout(() => { + if (state.selectedVmId !== uuid) return; + clearVmCredential(); + const current = state.vms.find((item) => String(item.uuid || "") === uuid); + if (current) renderVmCredentialStatus(current); + }, 30000); + } catch (error) { + if (state.selectedVmId === uuid) toast(error.message, "error"); + } finally { + if (state.selectedVmId === uuid) { + state.credentialBusy = false; + const current = state.vms.find((item) => String(item.uuid || "") === uuid); + if (current) renderVmCredentialStatus(current); + } + } +}); +byId("vm-detail-password-copy").addEventListener("click", async () => { + const uuid = state.selectedVmId; + const vm = state.vms.find((item) => String(item.uuid || "") === uuid); + if (!uuid || !vm?.password_available || state.credentialBusy) return; + state.credentialBusy = true; + renderVmCredentialStatus(vm); + try { + const password = state.credentialVisible && state.credentialVmId === uuid + ? state.credentialPassword : await readVmCredential(uuid); + if (!password || state.selectedVmId !== uuid) return; + await copyText(password); + if (state.selectedVmId === uuid) toast("初始 root 密码已复制,请妥善保管。", "success"); + } catch (error) { + if (state.selectedVmId === uuid) toast(error.message, "error"); + } finally { + if (state.selectedVmId === uuid) { + state.credentialBusy = false; + const current = state.vms.find((item) => String(item.uuid || "") === uuid); + if (current) renderVmCredentialStatus(current); + } + } +}); +byId("vm-metrics-range").addEventListener("change", (event) => { + const range = event.currentTarget.value; + if (!Object.hasOwn(VM_METRICS_RANGE_SECONDS, range)) return; + state.metricsRange = range; + stopVmMetrics(); + clearVmMetrics("正在加载所选时间范围的监控数据…"); + startVmMetrics(); +}); +window.addEventListener("resize", () => { + if (!metricViewVisible() || !state.metricsPayload) return; + if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer); + state.metricsResizeTimer = window.setTimeout(() => { + state.metricsResizeTimer = null; + if (metricViewVisible() && state.metricsPayload) renderVmMetrics(state.metricsPayload); + }, 120); +}); +document.addEventListener("visibilitychange", () => { + if (document.hidden) { + stopVmMetrics(); + clearVmCredential(); + const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId); + if (vm) renderVmCredentialStatus(vm); + } else startVmMetrics(); +}); +byId("vm-detail-back-button").addEventListener("click", () => { + showVmWorkspace(); + byId("search-input").focus(); +}); +byId("search-input").addEventListener("input", () => renderVMs()); +byId("state-filter").addEventListener("change", () => renderVMs()); +byId("create-button").addEventListener("click", openCreate); +byId("create-back").addEventListener("click", () => { + if (showVmWorkspace()) byId("vm-list-title").focus(); +}); +byId("reinstall-back").addEventListener("click", leaveReinstallPage); +byId("reinstall-cancel").addEventListener("click", leaveReinstallPage); +byId("rescue-back").addEventListener("click", leaveRescuePage); +byId("ssh-key-file").addEventListener("change", async (event) => { + const file = event.currentTarget.files?.[0]; + if (!file) return; + showError("ssh-key-form-error", ""); + try { + if (file.size > 16384) throw new Error("公钥文件不能超过 16 KiB;请选择 .pub 公钥文件,不要选择私钥。"); + const publicKey = (await file.text()).trim(); + if (!validSshPublicKey(publicKey)) throw new Error("文件内容不是受支持的单行 OpenSSH 公钥;请确认选择的是 .pub 文件而非私钥。"); + byId("ssh-key-public-key").value = publicKey; + if (!byId("ssh-key-name").value.trim()) byId("ssh-key-name").value = file.name.replace(/\.pub$/i, "").slice(0, 80); + } catch (error) { + showError("ssh-key-form-error", error.message); + } finally { + event.currentTarget.value = ""; + } +}); +byId("ssh-key-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("ssh-key-form-error", ""); + const name = byId("ssh-key-name").value.trim(); + const publicKey = byId("ssh-key-public-key").value.trim(); + if (!name || name.length > 80) { + showError("ssh-key-form-error", "请填写 1 至 80 个字符的公钥名称。"); + return; + } + if (!validSshPublicKey(publicKey)) { + showError("ssh-key-form-error", "请填写单行 OpenSSH 公钥,例如 ssh-ed25519 AAAA…;不要填写私钥。"); + return; + } + const button = byId("ssh-key-save-button"); + setButtonBusy(button, true, "正在保存…"); + try { + await api("/api/v1/ssh-keys", { method: "POST", body: { name, public_key: publicKey } }); + byId("ssh-key-form").reset(); + if (state.sshKeysLoad) await state.sshKeysLoad.catch(() => {}); + await loadSshKeys(); + toast("公钥已保存,创建云镜像虚拟机时可以直接选择。", "success"); + } catch (error) { + showError("ssh-key-form-error", error.message); + } finally { + setButtonBusy(button, false); + } +}); +for (const id of ["vm-open-ssh-keys", "reinstall-open-ssh-keys"]) { + byId(id).addEventListener("click", () => { + void showSshKeysWorkspace(id === "vm-open-ssh-keys" ? "create" : "reinstall"); + }); +} +for (const [inputId, hintId] of [["vm-root-password", "vm-root-password-hint"], ["reinstall-root-password", "reinstall-root-password-hint"]]) { + byId(inputId).addEventListener("input", () => updateRootPasswordHint(inputId, hintId)); +} +document.querySelectorAll('input[name="source"]').forEach((radio) => radio.addEventListener("change", () => { + showError("create-error", ""); + updateCreateSource(); + if (selectedCreateSource() === "cloud") { + void loadTemplates().catch((error) => showError("create-error", `无法加载云镜像模板:${error.message}`)); + void loadSshKeys().catch((error) => showError("create-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`)); + } +})); + +byId("template-import-form").addEventListener("submit", async (event) => { + event.preventDefault(); + if (!state.admin) return; + showError("template-import-error", ""); + const existingJobId = state.templateImportJobId; + const name = byId("template-name").value.trim(); + const rawUrl = byId("template-url").value.trim(); + const sha256 = byId("template-sha256").value.trim().toLowerCase(); + let url; + try { url = new URL(rawUrl); } catch { /* Validate below without displaying the supplied URL. */ } + if (!existingJobId && (!name || name.length > 64)) { + showError("template-import-error", "请填写不超过 64 个字符的模板名称。"); + return; + } + if (!existingJobId && (!url || url.origin !== "https://repo.almalinux.org" || url.username || url.password || url.search || url.hash + || !/^\/almalinux\/(9|10)\/cloud\/x86_64\/images\/AlmaLinux-\1-GenericCloud-[A-Za-z0-9._-]+\.x86_64\.qcow2$/.test(url.pathname))) { + showError("template-import-error", "目前仅支持 repo.almalinux.org 上的 AlmaLinux 9 / 10 x86_64 GenericCloud qcow2 HTTPS 地址。"); + return; + } + if (!existingJobId && !/^[a-f0-9]{64}$/.test(sha256)) { + showError("template-import-error", "请填写镜像发布方提供的 64 位 SHA-256 校验值。"); + return; + } + const button = byId("template-import-button"); + setButtonBusy(button, true, "正在检查后台导入…"); + try { + let jobId = existingJobId; + if (!jobId) { + const started = await api("/api/v1/vm-templates/import", { method: "POST", body: { name, url: url.href, sha256 } }); + jobId = String(started?.job_id || ""); + if (!jobId) throw new Error("面板未返回模板导入任务编号,请刷新模板列表确认结果。"); + state.templateImportJobId = jobId; + } + showTemplateImportStatus("宿主机正在后台下载并校验云镜像。离开页面不会取消任务,请稍候。"); + const completed = await waitForTemplateImport(jobId); + state.templateImportJobId = null; + showTemplateImportStatus(""); + await loadTemplates(); + byId("template-import-form").reset(); + toast("云镜像模板已导入,用户现在可以在创建页面选择。", "success"); + } catch (error) { + showTemplateImportStatus(state.templateImportJobId ? "暂时无法确认导入进度,任务可能仍在后台运行;稍后点击按钮继续查看。" : ""); + showError("template-import-error", error.message); + } finally { + setButtonBusy(button, false); + } +}); + +byId("rescue-template-upload-form").addEventListener("submit", async (event) => { + event.preventDefault(); + if (!state.admin || state.rescueUploading) return; + if (state.rescueImportJobId) { + state.rescueUploading = true; + setButtonBusy(byId("rescue-template-upload-button"), true, "正在查询导入…"); + void pollRescueImport(state.rescueImportJobId, ++state.rescueUploadPollToken); + return; + } + showError("rescue-template-upload-error", ""); + const name = byId("rescue-template-name").value.trim(); + const file = byId("rescue-template-file").files?.[0]; + if (!name || name.length > 64) { + showError("rescue-template-upload-error", "救援模版名称应为 1 至 64 个字符。"); + return; + } + if (!file || !/\.iso$/i.test(file.name) || file.size <= 0 || file.size > RESCUE_UPLOAD_MAX_BYTES) { + showError("rescue-template-upload-error", "请选择非空的 .iso 文件,且大小不能超过 8 GiB。"); + return; + } + const button = byId("rescue-template-upload-button"); + const epoch = state.sessionEpoch; + state.rescueUploading = true; + setButtonBusy(button, true, "正在上传 ISO…"); + showRescueImportStatus(`正在传输 ${formatRescueSize(file.size)} 的 ISO;请保持页面和网络连接。上传完成后宿主机会继续导入。`); + try { + const result = await api(`/api/v1/rescue-templates?name=${encodeURIComponent(name)}`, { + method: "POST", rawBody: file, contentType: "application/octet-stream", + }); + if (epoch !== state.sessionEpoch) return; + const jobId = String(result?.job_id || ""); + if (!jobId) throw new Error("上传结果没有任务编号。请先刷新模版列表确认结果,勿重复上传。"); + state.rescueImportJobId = jobId; + try { sessionStorage.setItem(rescueImportStorageKey(), jobId); } catch { /* Status remains visible in this tab. */ } + text("rescue-template-upload-button", "正在导入…"); + void pollRescueImport(jobId, ++state.rescueUploadPollToken); + } catch (error) { + state.rescueUploading = false; + showRescueImportStatus(""); + showError("rescue-template-upload-error", error.message); + setButtonBusy(button, false); + } +}); + +async function startRescueVmAction(exitMode) { + const vm = state.rescueTarget; + if (!vm || state.rescueInProgress) return; + const uuid = String(vm.uuid || ""); + const confirmationName = byId("rescue-confirm-name").value; + const templateId = byId("rescue-template-id").value; + showError("rescue-error", ""); + if (exitMode && ((!state.rescueActive && !state.rescueStaged) || !state.rescueCanExit)) { + showError("rescue-error", "当前无法安全退出救援模式,请刷新状态或联系管理员。"); + return; + } + if (!exitMode && (state.rescueActive || state.rescueStaged)) { + showError("rescue-error", "救援 ISO 已加载或预挂载,请先退出或取消救援。"); + return; + } + if (confirmationName !== vm.name) { + showError("rescue-error", "确认名称与虚拟机名称不一致,未执行救援操作。"); + byId("rescue-confirm-name").focus(); + return; + } + if (!exitMode && !state.rescueTemplates.some((item) => String(item.id) === templateId)) { + showError("rescue-error", "请选择当前可用的救援模版。"); + return; + } + const warning = exitMode + ? state.rescueStaged + ? `确认取消 ${vm.name} 的救援预挂载并卸载 ISO?面板会恢复原系统的启动配置。若原系统仍在运行,不会为取消预挂载而关机;若已关机,将从原系统盘启动。` + : `确认退出 ${vm.name} 的救援模式?运行中的虚拟机会正常关机,然后从原系统盘重启;服务将短暂中断。若正常关机超时,操作会停止且不会强制断电。救援模式下详情页强制操作不可用;可通过救援系统的 VNC 控制台手动关机,待显示“已关机”后重试退出救援。` + : `确认让 ${vm.name} 加载救援 ISO?面板会先预挂载 ISO 为下次完整开机的启动介质,再请求正常关机并开机。若正常关机失败或超时,但救援页显示“已预挂载”,可在本页确认风险后点“强制重启进入救援”;也可返回详情页手动“强制断电”再“开机”。“强制重置”不保证读取新保存的启动配置。面板不会自动强制断电。`; + if (!window.confirm(warning)) return; + const button = byId(exitMode ? "rescue-exit" : "rescue-submit"); + state.rescueInProgress = true; + setButtonBusy(button, true, "正在提交任务…"); + byId(exitMode ? "rescue-submit" : "rescue-exit").disabled = true; + byId("rescue-force-start").disabled = true; + const path = exitMode ? `/api/v1/vms/${encodeURIComponent(uuid)}/rescue/exit` + : `/api/v1/vms/${encodeURIComponent(uuid)}/rescue`; + const body = exitMode ? { confirmation_name: confirmationName } + : { template_id: templateId, confirmation_name: confirmationName }; + try { + const result = await api(path, { method: "POST", body }); + const jobId = String(result?.job_id || ""); + if (!jobId) throw new Error("面板未返回救援任务编号。请检查虚拟机状态,勿重复提交。"); + state.rescueJobId = jobId; + saveRescueJob(uuid, jobId); + text("rescue-status", "任务已提交,正在预挂载救援 ISO 并请求正常关机…"); + void pollVmRescueJob(jobId, uuid, ++state.rescuePollToken); + } catch (error) { + state.rescueInProgress = false; + showError("rescue-error", error.message); + void loadVmRescueState(uuid).catch(() => {}); + } finally { + setButtonBusy(button, false); + button.disabled = state.rescueInProgress; + } +} + +async function forceStartStagedRescue() { + const vm = state.rescueTarget; + if (!vm || state.rescueInProgress) return; + const uuid = String(vm.uuid || ""); + showError("rescue-error", ""); + if (!state.rescueStaged || !state.rescueCanExit) { + showError("rescue-error", "救援 ISO 尚未确认预挂载,不能强制启动;请先刷新救援状态。"); + return; + } + const confirmationName = byId("rescue-confirm-name").value; + if (confirmationName !== vm.name) { + showError("rescue-error", "确认名称与虚拟机名称不一致,未执行救援操作。"); + byId("rescue-confirm-name").focus(); + return; + } + const stopped = stateCategory(state.rescuePowerState) === "stopped"; + const warning = stopped + ? `确认让 ${vm.name} 从已预挂载的救援 ISO 开机?原系统盘不会删除,救援完成后需要退出救援才能恢复原系统启动。` + : `确认强制重启 ${vm.name} 进入救援?救援 ISO 已预挂载。面板将强制断电,再完整开机读取救援启动配置;强制断电可能导致未保存的数据丢失。此操作不是普通“强制重置”。`; + if (!window.confirm(warning)) return; + const button = byId("rescue-force-start"); + state.rescueInProgress = true; + setButtonBusy(button, true, stopped ? "正在启动救援…" : "正在强制重启…"); + byId("rescue-submit").disabled = true; + byId("rescue-exit").disabled = true; + try { + const result = await api(`/api/v1/vms/${encodeURIComponent(uuid)}/rescue/force-start`, { + method: "POST", + body: { confirmation_name: confirmationName, ack_data_loss: true }, + }); + const jobId = String(result?.job_id || ""); + if (!jobId) throw new Error("面板未返回救援任务编号。请检查虚拟机状态,勿重复提交。"); + state.rescueJobId = jobId; + saveRescueJob(uuid, jobId); + text("rescue-status", stopped ? "正在从预挂载的救援 ISO 开机…" : "正在强制断电并从救援 ISO 冷启动…"); + void pollVmRescueJob(jobId, uuid, ++state.rescuePollToken); + } catch (error) { + state.rescueInProgress = false; + showError("rescue-error", error.message); + void loadVmRescueState(uuid).catch(() => {}); + } finally { + setButtonBusy(button, false); + button.disabled = state.rescueInProgress; + } +} + +byId("rescue-form").addEventListener("submit", (event) => { + event.preventDefault(); + void startRescueVmAction(false); +}); +byId("rescue-force-start").addEventListener("click", () => void forceStartStagedRescue()); +byId("rescue-exit").addEventListener("click", () => void startRescueVmAction(true)); + +function ipv4Parts(value) { + if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(value)) return null; + const segments = value.split("."); + const parts = segments.map(Number); + return parts.every((part, index) => part >= 0 && part <= 255 && String(part) === segments[index]) ? parts : null; +} + +function ipv4Number(parts) { + return parts.reduce((accumulator, part) => ((accumulator << 8) | part) >>> 0, 0); +} + +function ipv4Text(number) { + return [number >>> 24, (number >>> 16) & 255, (number >>> 8) & 255, number & 255].join("."); +} + +function validPublicIpCidr(value) { + const match = /^([^/]+)\/(\d{1,2})$/.exec(value); + if (!match) return false; + const parts = ipv4Parts(match[1]); + const prefix = Number(match[2]); + if (!parts || prefix < 1 || prefix > 30) return false; + const [first, second] = parts; + if (first === 0 || first === 10 || first === 127 || first >= 224 || + (first === 100 && second >= 64 && second <= 127) || + (first === 169 && second === 254) || + (first === 172 && second >= 16 && second <= 31) || + (first === 192 && second === 168)) return false; + if (prefix <= 30) { + const address = ipv4Number(parts); + const hostMask = 2 ** (32 - prefix) - 1; + const host = address & hostMask; + if (host === 0 || host === hostMask) return false; + } + return true; +} + +function parsePublicPool(value) { + const match = /^([^/]+)\/(\d{1,2})$/.exec(value); + const parts = match && ipv4Parts(match[1]); + const prefix = match && Number(match[2]); + if (!parts || prefix < 24 || prefix > 30) return null; + if ((parts[0] === 192 && parts[1] === 0 && parts[2] === 2) + || (parts[0] === 198 && parts[1] === 51 && parts[2] === 100) + || (parts[0] === 203 && parts[1] === 0 && parts[2] === 113)) return null; + const mask = (0xffffffff << (32 - prefix)) >>> 0; + const inputAddress = ipv4Number(parts); + const network = (inputAddress & mask) >>> 0; + if (prefix === 24 && inputAddress !== network) return null; + const broadcast = (network | (~mask >>> 0)) >>> 0; + if (!validPublicIpCidr(`${ipv4Text(network + 1)}/${prefix}`) + || !validPublicIpCidr(`${ipv4Text(broadcast - 1)}/${prefix}`)) return null; + return { network, broadcast, prefix, cidr: `${ipv4Text(network)}/${prefix}` }; +} + +function refreshPublicPoolPreview() { + const value = byId("host-public-pool-cidr").value.trim(); + const pool = parsePublicPool(value); + const preview = byId("host-public-pool-preview"); + preview.hidden = !pool; + if (pool) { + preview.textContent = `实际网段:${pool.cidr};主机地址范围:${ipv4Text(pool.network + 1)}–${ipv4Text(pool.broadcast - 1)}。网关、保留和已用地址不会分配。`; + } else { + preview.textContent = ""; + } +} + +function validPoolMember(value, publicPoolCidr) { + const parts = ipv4Parts(value); + const pool = parsePublicPool(publicPoolCidr); + if (!parts || !pool) return false; + const address = ipv4Number(parts); + return address > pool.network && address < pool.broadcast; +} + +function validGatewayForCidr(gateway, publicIpCidr) { + const gatewayParts = ipv4Parts(gateway); + const [ip, prefixText] = publicIpCidr.split("/"); + const ipParts = ipv4Parts(ip); + const prefix = Number(prefixText); + if (!gatewayParts || !ipParts || !Number.isInteger(prefix) || prefix < 1 || prefix > 30 || gateway === ip) return false; + const mask = (0xffffffff << (32 - prefix)) >>> 0; + const gatewayNumber = ipv4Number(gatewayParts); + if ((gatewayNumber & mask) !== (ipv4Number(ipParts) & mask)) return false; + if (prefix <= 30) { + const hostMask = (~mask) >>> 0; + const host = gatewayNumber & hostMask; + if (host === 0 || host === hostMask) return false; + } + return true; +} + +function validSshPublicKey(value) { + return !/[\r\n]/.test(value) && /^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)) [A-Za-z0-9+/]{32,}={0,2}(?: [^\r\n]*)?$/.test(value); +} + +byId("create-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("create-error", ""); + const button = byId("create-submit"); + const data = new FormData(event.currentTarget); + const source = selectedCreateSource(); + const body = { + name: String(data.get("name") || "").trim(), + vcpu: Number(data.get("vcpu")), + memory_mib: Number(data.get("memory_mib")), + disk_gib: Number(data.get("disk_gib")), + network: String(data.get("network") || ""), + }; + if (source === "cloud") { + body.source = "cloud"; + body.template_id = String(data.get("template_id") || ""); + const automaticPublicIp = Boolean(configuredPublicPool()); + if (!automaticPublicIp) { + body.public_ip_cidr = String(data.get("public_ip_cidr") || "").trim(); + body.gateway = String(data.get("gateway") || "").trim(); + body.dns_servers = String(data.get("dns_servers") || "").split(/[\s,;]+/).filter(Boolean); + } + const selectedKeyId = selectedSshKeyId("vm-guest-ssh-key-cards"); + if (selectedKeyId) { + const keyId = Number(selectedKeyId); + if (!Number.isSafeInteger(keyId) || keyId <= 0 || !state.sshKeys.some((key) => Number(key.id) === keyId)) { + showError("create-error", "所选公钥已不可用,请刷新公钥列表或重新选择。"); + return; + } + body.guest_ssh_key_id = keyId; + } + if (!body.network.startsWith("bridge:")) { + showError("create-error", "公网云镜像需要 Linux 网桥。请先在宿主机设置中配置 bridge:br0 等网桥。"); + return; + } + if (!body.template_id) { + showError("create-error", state.admin ? "请先选择已导入的云镜像版本;如无可用镜像,请到“云镜像模板”页面导入。" : "请先选择云镜像版本;如无可用镜像,请联系管理员导入。"); + return; + } + if (!automaticPublicIp && !validPublicIpCidr(body.public_ip_cidr)) { + showError("create-error", "请填写有效的公网 IPv4/CIDR,例如已分配给你的地址和 /24 或 /28 前缀;不能填写网段或广播地址。"); + return; + } + if (!automaticPublicIp && !validGatewayForCidr(body.gateway, body.public_ip_cidr)) { + showError("create-error", "请填写与虚拟机 IP 同网段的有效网关 IPv4,且不能与虚拟机 IP 相同。非同网段网关暂不支持。"); + return; + } + if (!automaticPublicIp && (!body.dns_servers.length || body.dns_servers.length > 4 || !body.dns_servers.every((address) => ipv4Parts(address)))) { + showError("create-error", "请填写 1 至 4 个有效的 DNS IPv4 地址,用逗号或空格分隔。"); + return; + } + const requestedPassword = String(data.get("root_password") || ""); + const passwordIssue = manualRootPasswordIssue(requestedPassword); + if (passwordIssue) { + showError("create-error", passwordIssue); + byId("vm-root-password").focus(); + return; + } + if (requestedPassword) body.root_password = requestedPassword; + } else { + body.iso = String(data.get("iso") || ""); + if (!body.network || !body.iso) { + showError("create-error", "请先选择可用的虚拟网络或网桥,以及 ISO 镜像。"); + return; + } + } + data.delete("root_password"); + byId("vm-root-password").value = ""; + updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); + setButtonBusy(button, true, "正在创建…"); + try { + const autoPassword = source === "cloud" && !body.root_password; + const createdVm = await api("/api/v1/vms", { method: "POST", body }); + showVmWorkspace(); + const createdIp = String(createdVm?.public_ip_cidr || "").split("/")[0]; + toast(autoPassword + ? `虚拟机 ${body.name} 创建成功${createdIp ? `,公网 IP:${createdIp}` : ""}。初始 root 密码可在虚拟机详情页查看。` + : `虚拟机 ${body.name} 创建成功${createdIp ? `,公网 IP:${createdIp}` : ""}。`, "success"); + await loadVMs(true); + window.setTimeout(() => void loadVMs(true), 1200); + } catch (error) { + showError("create-error", error.message); + } finally { + delete body.root_password; + byId("vm-root-password").value = ""; + updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); + setButtonBusy(button, false); + } +}); + +byId("reinstall-form").addEventListener("submit", async (event) => { + event.preventDefault(); + const vm = state.reinstallTarget; + if (!vm || state.reinstallInProgress) return; + showError("reinstall-error", ""); + const templateId = byId("reinstall-template").value; + const selectedKeyId = selectedSshKeyId("reinstall-ssh-key-cards"); + const rootPassword = byId("reinstall-root-password").value; + const confirmationName = byId("reinstall-confirm-name").value; + if (!templateId) { + showError("reinstall-error", state.admin ? "请先选择已导入的云镜像版本;如无可用镜像,请到“云镜像模板”页面导入。" : "请先选择云镜像版本;如无可用镜像,请联系管理员导入。"); + return; + } + if (selectedKeyId && !state.sshKeys.some((key) => String(key.id) === selectedKeyId)) { + showError("reinstall-error", "所选公钥已不可用,请刷新公钥列表并重试。"); + return; + } + const passwordIssue = manualRootPasswordIssue(rootPassword); + if (passwordIssue) { + showError("reinstall-error", passwordIssue); + byId("reinstall-root-password").focus(); + return; + } + if (confirmationName !== vm.name) { + showError("reinstall-error", "确认名称与虚拟机名称不一致,未执行重装。"); + return; + } + const button = byId("reinstall-submit"); + const body = { + template_id: templateId, + confirmation_name: confirmationName, + }; + if (selectedKeyId) body.ssh_key_id = Number(selectedKeyId); + if (rootPassword) body.root_password = rootPassword; + state.reinstallInProgress = true; + state.reinstallExpectGeneratedPassword = !selectedKeyId && !rootPassword; + byId("reinstall-back").disabled = true; + byId("reinstall-cancel").disabled = true; + setButtonBusy(button, true, "正在提交…"); + try { + const started = await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/reinstall`, { method: "POST", body }); + const jobId = String(started?.job_id || ""); + if (!jobId) throw new Error("面板未返回重装任务编号,请先检查虚拟机状态,勿重复提交。"); + state.reinstallJobId = jobId; + saveReinstallJob(jobId); + byId("reinstall-fields").hidden = true; + byId("reinstall-progress").hidden = false; + byId("reinstall-cancel").hidden = true; + byId("reinstall-submit").hidden = true; + text("reinstall-phase", "重装任务已提交,正在检查宿主机状态…"); + const token = ++state.reinstallPollToken; + void pollReinstallJob(jobId, token); + } catch (error) { + state.reinstallInProgress = false; + byId("reinstall-back").disabled = false; + byId("reinstall-cancel").disabled = false; + showError("reinstall-error", error.message); + } finally { + delete body.root_password; + byId("reinstall-root-password").value = ""; + updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); + setButtonBusy(button, false); + } +}); + +byId("reinstall-copy-password").addEventListener("click", async () => { + const password = byId("reinstall-generated-password").textContent; + if (!password) return; + try { + await navigator.clipboard.writeText(password); + toast("root 密码已复制,请安全保存。", "success"); + } catch { + toast("浏览器无法复制,请手动选中并保存密码。", "error"); + } +}); +byId("reinstall-done").addEventListener("click", async () => { + if (!state.reinstallPasswordPendingAck) { + leaveReinstallPage(); + return; + } + const jobId = state.reinstallJobId; + if (!jobId) { + showError("reinstall-error", "无法确认此密码已保存,请立即手动复制,并检查面板任务状态。"); + return; + } + const button = byId("reinstall-done"); + setButtonBusy(button, true, "正在确认…"); + try { + const result = await api(`/api/v1/reinstall-jobs/${encodeURIComponent(jobId)}/ack-password`, { method: "POST" }); + if (result?.acknowledged !== true) throw new Error("面板未确认密码已经清除,请稍后重试。"); + state.reinstallPasswordPendingAck = false; + clearSavedReinstallJob(); + leaveReinstallPage(); + } catch (error) { + showError("reinstall-error", `确认密码失败:${error.message}。密码仍在此页面中,请先安全保存后重试。`); + } finally { + setButtonBusy(button, false); + } +}); +byId("reinstall-retry").addEventListener("click", () => { + const jobId = state.reinstallJobId; + if (!jobId) return; + state.reinstallInProgress = true; + byId("reinstall-back").disabled = true; + byId("reinstall-result").hidden = true; + byId("reinstall-progress").hidden = false; + byId("reinstall-retry").hidden = true; + byId("reinstall-done").hidden = true; + text("reinstall-phase", "正在重新查询已有重装任务…"); + const token = ++state.reinstallPollToken; + void pollReinstallJob(jobId, token); +}); +byId("reinstall-forget").addEventListener("click", () => { + if (!window.confirm("请先在宿主机核对虚拟机、新旧系统盘和登录方式。放弃恢复后,本标签页将不再查询此任务,尚未领取的自动 root 密码也可能无法找回。确定放弃吗?")) return; + clearSavedReinstallJob(); + leaveReinstallPage(); +}); + +byId("delete-form").addEventListener("submit", async (event) => { + event.preventDefault(); + const vm = state.deleteTarget; + if (!vm) return; + showError("delete-error", ""); + const button = byId("delete-submit"); + setButtonBusy(button, true, "正在删除…"); + const deleteDisks = byId("delete-disks").checked; + try { + await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}?delete_disks=${deleteDisks}`, { method: "DELETE" }); + closeModal(); + toast(`${vm.name || vm.uuid} 已删除${deleteDisks ? ",磁盘已一并删除" : ""}。`, "success"); + if (state.selectedVmId === vm.uuid) { + showVmWorkspace(); + byId("vm-list-title").focus(); + } + await loadVMs(true); + } catch (error) { + showError("delete-error", error.message); + } finally { + setButtonBusy(button, false); + } +}); + +byId("confirm-submit").addEventListener("click", async () => { + const target = state.confirmTarget; + if (!target) return; + const button = byId("confirm-submit"); + setButtonBusy(button, true); + try { + const succeeded = await runAction(target.vm, target.action); + if (succeeded) closeModal(); + else showError("confirm-error", "操作未完成,请检查宿主机状态后重试。"); + } finally { + setButtonBusy(button, false); + } +}); + +byId("console-cad").addEventListener("click", () => state.rfb?.sendCtrlAltDel()); +byId("console-fullscreen").addEventListener("click", async () => { + const stage = byId("console-stage"); + try { + if (document.fullscreenElement) await document.exitFullscreen(); + else await stage.requestFullscreen(); + } catch (error) { toast(`无法进入全屏:${error.message}`, "error"); } +}); +byId("console-password-form").addEventListener("submit", (event) => { + event.preventDefault(); + if (!state.rfb) return; + state.rfb.sendCredentials({ password: byId("console-password").value }); + byId("console-password").value = ""; + byId("console-password-form").hidden = true; + text("console-status", "正在验证 VNC 密码…"); +}); + +function requestCloseModal() { + closeModal(); +} + +document.querySelectorAll("[data-close-modal]").forEach((button) => button.addEventListener("click", requestCloseModal)); +document.querySelectorAll(".modal-backdrop").forEach((backdrop) => backdrop.addEventListener("click", (event) => { + if (event.target === backdrop) requestCloseModal(); +})); +document.addEventListener("keydown", (event) => { + if (!state.activeModal) return; + if (event.key === "Escape") { requestCloseModal(); return; } + if (event.key !== "Tab") return; + const focusables = Array.from(state.activeModal.querySelectorAll("button:not(:disabled):not([hidden]),input:not(:disabled):not([hidden]),select:not(:disabled):not([hidden])")) + .filter((element) => element.getClientRects().length); + if (!focusables.length) return; + const first = focusables[0]; + const last = focusables[focusables.length - 1]; + if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } + else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } +}); + +void initialize(); diff --git a/engine/static/centos-icon.svg b/engine/static/centos-icon.svg new file mode 100644 index 00000000..ba433b4e --- /dev/null +++ b/engine/static/centos-icon.svg @@ -0,0 +1 @@ + diff --git a/engine/static/debian-icon.svg b/engine/static/debian-icon.svg new file mode 100644 index 00000000..7fa03875 --- /dev/null +++ b/engine/static/debian-icon.svg @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + diff --git a/engine/static/index.html b/engine/static/index.html new file mode 100644 index 00000000..7c3e9873 --- /dev/null +++ b/engine/static/index.html @@ -0,0 +1,493 @@ + + + + + + + VirtPilot · 虚拟机管理 + + + + +
+ + 正在连接控制面板… +
+ +
+
+
VirtPilot
+ FIRST RUN SETUP +

先连接数据库,
再开始管理。

+

面板业务数据保存在 MariaDB 中。只需在首次启用时填写连接信息,无需预先编辑面板配置文件。

+
01 · 配置数据库02 · 创建初始用户03 · 授予管理员权限
+
+
+
+ 步骤 01 / 03 +

连接 MariaDB

+

请先准备可连接的数据库与账号。连接信息只提交给面板服务,不会保存在浏览器中。

+

请先完成你自己的 HTTPS 反向代理,并核对证书和域名,再输入数据库密码与初始化令牌。

+
+ + + + + + + + + + + + + + +
+

数据库需由你预先创建并授权;面板不会自动安装 MariaDB。初始化令牌完成初始用户创建后失效。

+
+
+
+ +
+
+
VirtPilot
+ FIRST RUN SETUP +

欢迎使用
VirtPilot

+

完成数据库连接后先创建初始用户,再由你在数据库中将其 admin 字段改为管理员权限。

+
01 · 配置数据库02 · 创建初始用户03 · 授予管理员权限
+
+
+
+ 步骤 02 / 03 +

创建初始用户

+

使用面板首次启动时在终端输出的一次性初始化令牌。完成后令牌将失效。

+

安全检查:请先完成你自己的 HTTPS 反向代理,并确认浏览器连接的是你信任的证书和域名,再输入令牌、密码或宿主机私钥。

+
+ + + + + + + + + + +
+

初始用户默认没有管理员权限。创建后请由你在数据库中将该用户 admin 字段设为 1,并手动补充登录邮箱,再用邮箱登录配置 SMTP 和宿主机。面板账号与宿主机 root 账号相互独立。

+
+
+
+ +
+ + +
+ +
+
VirtPilot
+
ACCOUNT STATUS

等待管理员审核

邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机。

+
+ +
+
+
VirtPilot
+
+
+
+
步骤 03 / 03

连接 libvirt 宿主机

填入现有的 root SSH 信息,面板将通过 libvirt API 管理远端虚拟机。

+
+
+
1

SSH 连接信息

使用宿主机已有的 root 私钥,不创建额外的系统账号。

+
+
+
+
+
用于展示这台宿主机上的虚拟机所在地区;留空时显示“未设置”。
+
+
可直接填写宿主机上的绝对路径,如 /home/kvm;也兼容现有 libvirt 存储池名称。
+
供创建虚拟机安装系统时选择;填写宿主机上的绝对路径,如 /home/iso,或现有存储池名称。
+
专供上传救援模版使用,不能与安装 ISO 目录相同,也不要通过软链接或绑定挂载指向同一目录。请先在宿主机创建目录;面板只注册已存在的目录,不会自动创建。
+
libvirt 虚拟网络填名称;宿主机现有 Linux 网桥 br0 填 bridge:br0。
+
+
公网 IPv4 地址池仅用于云镜像虚拟机;配置后面板只从填写的服务商获配网段自动分配地址。请按真实前缀填写,不要把仅获配的 /28 误填成 /24。
+
+
可填网段或段内地址/前缀,例如 123.123.123.113/28 会保存为 123.123.123.112/28;留空则手动指定公网 IP。
+
网关不会被分配给虚拟机。
+
只影响虚拟机内的网络掩码,不扩大可分配 IP 范围。如果你的服务商要求客体使用 /24,而获配地址池是 /28,这里填 24。
+
填写 1 至 4 个 DNS 地址,用逗号或空格分隔。
+
这些地址不会自动分配。请填写面板之外已占用的地址;若宿主机地址填的是域名,也请把宿主机自身的公网 IP 填在这里。
+
+
+
仅通过 HTTPS 传输并保存在面板服务器。请确保这把密钥已在宿主机 root 账号上获得授权。
+
未选择文件;已保存的密钥不会在这里显示。
+
保存时会加密写入面板数据库,供重启后自动连接和后台持续采样;面板不会回显口令或写入浏览器存储。
+
+
+
+ +
+
+
2

核对 SSH 主机指纹

先扫描面板看到的公钥,再与宿主机控制台显示的指纹对比。

+ + +

请在宿主机 B 的控制台执行 ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub 并逐字核对。当前仅支持 Ed25519 主机密钥;不要仅凭网页显示就信任该指纹。

+ +
+
+
3

测试并保存

测试 root SSH、libvirt、存储池和虚拟网络是否可用。

+

尚未测试连接

+ +
+

root 私钥拥有很高权限。请保护面板管理员密码,仅通过 HTTPS 访问面板,并限制能访问面板的网络范围。

+
+
+
+
+
+ +
+
+
VirtPilot
+
+
+
+
+ HOST KEY LOCKED +

解锁宿主机 SSH 私钥

+

宿主机 的私钥尚未自动解锁。请输入口令以恢复连接;若要重启后自动连接,请随后在“宿主机设置”中重新保存口令。

+
+ + + + +
+

在这里输入只用于本次解锁;在“宿主机设置”重新保存后,口令会加密写入数据库供后台使用。面板不会将口令写入浏览器存储;请通过 HTTPS 连接面板。

+ + +
+
+
+ + + + + + + + + +
+ + diff --git a/engine/static/styles.css b/engine/static/styles.css new file mode 100644 index 00000000..37cda1e9 --- /dev/null +++ b/engine/static/styles.css @@ -0,0 +1,193 @@ +:root{font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif;color:#15243a;background:#f4f7fb;font-synthesis:none;-webkit-font-smoothing:antialiased} +*{box-sizing:border-box} +[hidden]{display:none!important} +body{margin:0;min-width:320px} +button,input,select{font:inherit} +button{cursor:pointer} +button:disabled{cursor:not-allowed;opacity:.52} +input,select{outline:none} +input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px} +.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} +.brand-mark{display:inline-flex;width:34px;height:34px;align-items:center;justify-content:center;border-radius:10px;background:#2ac6ca;box-shadow:0 7px 17px rgba(16,172,184,.18);flex:none} +.brand-mark:before,.brand-mark span{content:"";display:block;width:11px;height:17px;border:3px solid #0c2a3f;transform:skewY(-22deg);border-radius:2px} +.brand-mark:before{border-right:0;margin-right:-1px} +.brand-mark span{border-left:0;margin-left:-1px} +.boot-screen{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;gap:13px;background:#f4f7fb;color:#607087;font-size:14px;z-index:50} +.login-layout{min-height:100vh;display:grid;grid-template-columns:minmax(390px,48%) 1fr;background:#fff} +.login-art{position:relative;min-height:650px;overflow:hidden;background:radial-gradient(circle at 78% 44%,#174c64 0,#122d44 36%,#0d1d31 75%);color:#fff} +.login-art-grid{position:absolute;inset:0;background-image:linear-gradient(rgba(143,221,226,.065) 1px,transparent 1px),linear-gradient(90deg,rgba(143,221,226,.065) 1px,transparent 1px);background-size:50px 50px;mask-image:linear-gradient(90deg,transparent,black)} +.login-art-inner{position:relative;height:100%;min-height:650px;display:flex;flex-direction:column;justify-content:space-between;padding:43px clamp(38px,5vw,90px);z-index:2} +.login-art-brand{display:flex;gap:13px;align-items:center;font-weight:800;font-size:23px;letter-spacing:-.6px} +.login-art-copy{max-width:500px;margin-bottom:70px} +.eyebrow{display:inline-block;color:#159da9;font-size:11px;letter-spacing:.14em;font-weight:800} +.eyebrow.light{color:#53dce0} +.login-art-copy h1{font-size:clamp(38px,4vw,62px);line-height:1.25;letter-spacing:-1.8px;margin:20px 0 19px;font-weight:750} +.login-art-copy p{max-width:380px;color:#bbd1dc;font-size:16px;line-height:1.85;margin:0} +.login-art-footer{color:#bed5dc;font-size:12px;letter-spacing:.04em;display:flex;align-items:center;gap:10px} +.online-dot,.tiny-dot,.connection-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#35d49b;box-shadow:0 0 0 4px rgba(53,212,155,.12)} +.art-orbit{position:absolute;border:1px solid rgba(90,220,220,.19);border-radius:50%;width:560px;height:560px;right:-220px;top:20%;transform:rotate(-28deg)} +.orbit-two{width:390px;height:390px;right:-135px;top:29%;border-color:rgba(90,220,220,.27)} +.art-core{position:absolute;right:5%;top:40%;width:240px;height:240px;transform:rotate(-22deg);opacity:.72} +.art-core span{position:absolute;display:block;border-radius:23px;width:140px;height:140px;border:1px solid rgba(82,220,224,.3);background:linear-gradient(135deg,rgba(75,205,213,.2),rgba(13,35,57,.1));box-shadow:0 25px 55px rgba(0,0,0,.18)} +.art-core span:nth-child(2){top:43px;left:38px}.art-core span:nth-child(3){top:86px;left:76px;background:linear-gradient(135deg,rgba(62,210,210,.42),rgba(9,46,67,.45))} +.login-form-side{display:flex;align-items:center;justify-content:center;padding:40px} +.login-card{width:min(100%,410px)} +.login-mobile-brand{display:none} +.login-card h2{font-size:34px;letter-spacing:-1px;margin:14px 0 8px} +.muted{color:#7a8798;margin:0 0 43px;font-size:14px;line-height:1.7} +.form-stack{display:flex;flex-direction:column} +.form-stack label,.field label,.console-password label{font-size:13px;font-weight:700;color:#34445a;margin:0 0 9px} +.form-stack input,.field input,.field select,.console-password input{height:46px;width:100%;border:1px solid #dce4eb;background:#fff;border-radius:9px;padding:0 13px;color:#15243a;transition:border-color .15s,box-shadow .15s} +.form-stack input:focus,.field input:focus,.field select:focus,.console-password input:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none} +.form-stack input::placeholder,.field input::placeholder{color:#a6b1be} +.form-stack input{margin-bottom:23px} +.form-error{color:#bf3e48;font-size:13px;line-height:1.5;margin:0 0 16px} +.button{border:1px solid transparent;display:inline-flex;align-items:center;justify-content:center;gap:8px;border-radius:9px;padding:10px 17px;min-height:41px;background:#fff;color:#304158;font-size:13px;font-weight:700;white-space:nowrap;transition:transform .15s,box-shadow .15s,background .15s,border-color .15s} +.button:not(:disabled):hover{transform:translateY(-1px)} +.button-primary{background:#0f9eaa;color:#fff;box-shadow:0 8px 17px rgba(15,158,170,.16)} +.button-primary:not(:disabled):hover{background:#0b8c98;box-shadow:0 10px 19px rgba(15,158,170,.22)} +.button-outline{border-color:#d7e0e8;background:#fff;color:#445368} +.button-outline:not(:disabled):hover{border-color:#aebfc8;background:#f8fbfc} +.button-ghost{background:transparent;color:#6a798d} +.button-ghost:not(:disabled):hover{background:#f3f6f9} +.button-danger{background:#d94350;color:#fff} +.button-danger:not(:disabled):hover{background:#c73441} +.button.small{min-height:34px;padding:7px 11px;font-size:12px} +.login-submit{height:48px;justify-content:space-between;padding:0 17px;margin-top:6px;font-size:14px} +.login-submit span{font-size:20px;font-weight:400} +.login-hint{margin:27px 0 0;color:#9aa5b2;font-size:12px;line-height:1.7} +.auth-switch{display:flex;align-items:center;gap:5px;margin:20px 0 0;color:#708093;font-size:12px}.auth-switch button{padding:2px 0;border:0;background:transparent;color:#0f8f9a;font-size:12px;font-weight:800}.auth-switch button:hover{text-decoration:underline}.register-code-row{display:flex;align-items:flex-start;gap:9px;margin-bottom:19px}.register-code-row input{min-width:0;flex:1;margin:0}.register-code-row .button{flex:none;height:46px}.register-code-status,.smtp-status{margin:0 0 16px;padding:10px 12px;border-radius:8px;background:#ecf8f7;color:#267d78;font-size:12px;line-height:1.6}.smtp-status{margin:0}.smtp-card{max-width:780px;margin-bottom:18px}.smtp-card .form-error{margin:0}.pending-users-list{display:grid;gap:10px}.pending-users-list>.muted{margin:0}.pending-user-row{display:flex;align-items:center;justify-content:space-between;gap:15px;border:1px solid #e2ebef;border-radius:9px;padding:13px 15px}.pending-user-details{min-width:0;display:grid;gap:4px;overflow-wrap:anywhere}.pending-user-details strong{font-size:13px;color:#2f455a}.pending-user-details span{font-size:12px;color:#5b7285}.pending-user-details small{font-size:11px;color:#9aabba} +.setup-layout{display:grid;grid-template-columns:minmax(330px,40%) 1fr;min-height:100vh;background:#fff} +.setup-intro{min-height:640px;background:radial-gradient(circle at 90% 95%,#1b5d68,#122d44 40%,#0e1e31 85%);color:#fff;padding:clamp(35px,5vw,75px);display:flex;flex-direction:column;align-items:flex-start} +.setup-brand,.host-brand{display:flex;align-items:center;gap:11px;font-size:22px;font-weight:800;letter-spacing:-.5px}.setup-brand{margin-bottom:auto} +.setup-intro h1{font-size:clamp(40px,4vw,62px);line-height:1.2;margin:18px 0}.setup-intro p{max-width:420px;color:#bed1dc;font-size:15px;line-height:1.85;margin:0 0 47px} +.setup-steps{display:flex;gap:12px;flex-wrap:wrap;width:100%;margin-top:auto}.setup-steps span{padding:10px 15px;border:1px solid #3b596a;border-radius:8px;color:#91aebf;font-size:12px;font-weight:700}.setup-steps .current{background:#1b5260;border-color:#2e8791;color:#6be0df} +.setup-form-side{display:flex;align-items:center;justify-content:center;padding:45px clamp(24px,5vw,80px)}.setup-card{width:min(100%,440px)}.setup-card h2{font-size:31px;letter-spacing:-.8px;margin:13px 0 9px}.setup-card .muted{margin-bottom:29px}.setup-submit{height:47px;justify-content:space-between;margin-top:6px}.setup-submit span{font-size:20px;font-weight:400}.setup-note{font-size:11px;line-height:1.8;color:#9aa8b5;margin:24px 0 0} +.setup-security-note{font-size:11px;line-height:1.75;color:#496372;background:#edf8f8;border:1px solid #d2eeee;border-radius:9px;padding:11px 13px;margin:-10px 0 23px} +.host-layout{min-height:100vh;background:#f4f7fb}.host-topbar{height:75px;background:#fff;border-bottom:1px solid #e7edf2;padding:0 clamp(22px,5vw,76px);display:flex;align-items:center;justify-content:space-between}.host-brand{font-size:20px}.host-topbar-actions{display:flex;align-items:center;gap:14px}.host-user{font-size:12px;color:#65778a;font-weight:700} +.host-content{max-width:1380px;padding:39px clamp(22px,5vw,76px) 70px;margin:0 auto}.host-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;margin-bottom:29px}.host-heading h1{font-size:29px;letter-spacing:-.6px;margin:8px 0}.host-heading p{color:#8090a0;font-size:13px;line-height:1.6;margin:0} +.host-columns{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(350px,.85fr);gap:19px;align-items:start}.host-side-stack{display:grid;gap:19px}.host-card{background:#fff;border:1px solid #e6edf2;border-radius:13px;padding:26px;box-shadow:0 10px 30px rgba(19,42,65,.027)}.host-card-heading{display:flex;gap:12px;align-items:flex-start;margin-bottom:24px}.host-card-number{display:flex;align-items:center;justify-content:center;flex:none;width:31px;height:31px;background:#e7f8f8;color:#0e919b;border-radius:9px;font-size:13px;font-weight:800}.host-card-heading h2{font-size:17px;margin:2px 0 5px;letter-spacing:-.2px}.host-card-heading p{font-size:11px;color:#91a1b0;margin:0;line-height:1.6} +.host-card textarea{width:100%;min-height:125px;padding:12px 13px;border:1px solid #dce4eb;border-radius:9px;color:#15243a;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;resize:vertical;background:#fff}.host-card textarea:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none}.host-card input[type=file]{height:auto;min-height:43px;padding:9px;font-size:11px}.host-card input[type=file]::file-selector-button{border:0;border-radius:6px;padding:5px 10px;margin-right:9px;background:#e9f6f6;color:#137e89;font-weight:700;cursor:pointer} +.host-public-pool{grid-column:1/-1;border-top:1px solid #e8eef2;padding-top:18px}.host-public-pool-heading{margin-bottom:16px}.host-public-pool-heading strong{display:block;color:#34445a;font-size:13px}.host-public-pool-heading small{display:block;margin-top:6px;color:#8798a7;font-size:10px;line-height:1.6}.host-public-pool textarea{min-height:78px} +.fingerprint-result{margin:18px 0 14px;padding:14px;border:1px solid #b9e6e5;background:#effafa;border-radius:9px}.fingerprint-result>span{display:block;color:#417c85;font-size:11px;font-weight:700;margin-bottom:8px}.fingerprint-result code{display:block;color:#1b5260;font-size:12px;font-weight:800;line-height:1.7;overflow-wrap:anywhere}.host-security-note{font-size:11px;color:#8191a1;line-height:1.75;margin:16px 0 0}.host-security-note code{color:#41566e;font-size:10px;overflow-wrap:anywhere}.host-confirm{margin-top:17px;background:#f0fbf8;border-color:#cce9e0}.host-confirm strong{color:#217d6e}.host-confirm small{color:#659a90} +.host-test-status{font-size:12px;color:#708095;background:#f4f7fa;padding:12px 14px;border-radius:8px;line-height:1.55;margin:0 0 15px}.host-test-status.success{background:#e7f8ef;color:#1d9168}.host-test-status.warning{background:#fff4e6;color:#9a641d}.host-submit-actions{display:flex;gap:9px;flex-wrap:wrap}.host-submit-actions .button{flex:1}.host-card .form-error{margin:0 0 13px} +.update-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:19px;align-items:start}.update-grid .host-card{min-width:0}.update-grid .form-stack input{margin-bottom:17px}.update-grid .form-stack .field-hint{display:block;color:#8395a5;font-size:11px;line-height:1.6;margin:-7px 0 17px}.update-grid .form-stack .button{align-self:flex-start}.update-grid .host-test-status{margin-top:17px;overflow-wrap:anywhere}.update-versions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.update-versions>div{border:1px solid #e2ebf0;border-radius:9px;padding:13px;background:#fbfdfd;min-width:0}.update-versions span{display:block;color:#8291a1;font-size:11px;margin-bottom:9px}.update-versions strong{display:block;color:#284459;font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere} +.update-grid .form-stack input[readonly]{background:#f4f7f9;color:#6c7d8d} +.ssh-keys-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);gap:19px;align-items:start}.ssh-keys-grid .host-card{min-width:0}.ssh-keys-grid .form-stack .button{align-self:flex-start}.ssh-keys-grid .form-stack textarea{margin-bottom:19px}.ssh-key-file-hint{display:block;color:#8b9bab;font-size:11px;line-height:1.5;margin:-14px 0 20px}.ssh-keys-list{display:grid;gap:11px}.ssh-keys-list>.muted{margin:0}.ssh-key-row{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:14px;border:1px solid #e2ebef;border-radius:9px;background:#fbfdfd}.ssh-key-details{min-width:0;display:grid;gap:5px}.ssh-key-details strong{font-size:13px;color:#2b4358;overflow-wrap:anywhere}.ssh-key-details code{font-size:11px;color:#3b7a87;overflow-wrap:anywhere}.ssh-key-details small{font-size:10px;color:#95a4b2}.ssh-key-actions{display:flex;flex:none;gap:7px}.ssh-key-delete{color:#b94b57;border-color:#efd8dc} +.ssh-key-picker-title{display:block;color:#34445a;font-size:12px;font-weight:700}.ssh-key-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:10px}.ssh-key-option{display:flex;align-items:center;width:100%;min-width:0;min-height:74px;padding:12px 14px;text-align:left;border:1px solid #dce4eb;border-radius:9px;background:#fff;color:#334a5f;cursor:pointer}.ssh-key-option strong{font-size:12px;line-height:1.5;overflow-wrap:anywhere}.ssh-key-option[aria-pressed="true"]{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.ssh-key-option:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.ssh-key-picker-empty{grid-column:1/-1;margin:0;color:#8b9bab;font-size:11px}.ssh-key-picker-manage{margin-top:9px;padding:0;border:0;background:transparent;color:#148c98;font-size:11px;font-weight:700;cursor:pointer}.ssh-key-picker-manage:hover{text-decoration:underline}.field small.root-password-hint-error{color:#b73e4c}.field small.root-password-hint-success{color:#247f67} +@media(max-width:510px){.ssh-key-picker{grid-template-columns:1fr}} +.unlock-content{min-height:calc(100vh - 75px);display:flex;align-items:center;justify-content:center;padding:40px 24px}.unlock-card{width:min(100%,480px);padding:35px}.unlock-card h1{font-size:28px;letter-spacing:-.5px;margin:12px 0}.unlock-card .muted{margin:0 0 27px}.unlock-card .muted strong{color:#30445a;overflow-wrap:anywhere}.unlock-submit{width:100%;min-height:46px}.unlock-settings-button{margin-top:18px;padding-left:0} +.dashboard{min-height:100vh;display:grid;grid-template-columns:244px minmax(0,1fr)} +.sidebar{position:sticky;top:0;height:100vh;background:#101d2c;color:#d2dce6;padding:32px 15px 22px;display:flex;flex-direction:column} +.sidebar-brand{display:flex;align-items:center;gap:11px;padding:0 13px 46px;font-size:19px;color:#fff;letter-spacing:-.3px;font-weight:800} +.sidebar-brand small{display:block;color:#668197;font-size:8px;letter-spacing:.2em;margin-top:2px} +.sidebar-section-label{color:#64798f;text-transform:uppercase;letter-spacing:.14em;font-size:10px;font-weight:800;margin:0 15px 16px} +.sidebar-link{height:43px;display:flex;align-items:center;gap:13px;padding:0 14px;border-radius:9px;color:#8da2b6;font-size:13px;font-weight:700} +.sidebar-button{width:100%;border:0;background:transparent;text-align:left;font:inherit;cursor:pointer}.sidebar-button:hover{background:#1a3445;color:#d0eeee} +.sidebar-link.active{background:#1d3949;color:#57d4d3} +.nav-icon{font-size:20px;line-height:1}.nav-arrow{margin-left:auto;font-size:20px;opacity:.7} +.sidebar-bottom{margin-top:auto} +.host-panel{display:flex;align-items:center;gap:10px;padding:14px 11px;border:1px solid #274050;border-radius:10px;background:#172c3e} +.host-panel-icon{width:31px;height:31px;border-radius:8px;background:#213e4e;color:#5fd4d1;display:flex;align-items:center;justify-content:center;font-size:20px} +.host-panel strong,.host-panel span{display:block}.host-panel strong{font-size:11px;color:#dce8ec}.host-panel div:nth-child(2) span{font-size:10px;color:#8ca6b6;margin-top:3px} +.host-panel .connection-dot{margin-left:auto;width:7px;height:7px;box-shadow:none;flex:none}.host-panel .connection-dot.offline{background:#e68a7d} +.sidebar-caption{font-size:10px;color:#577086;margin:20px 10px 0;letter-spacing:.06em} +.main-area{min-width:0} +.topbar{height:74px;background:#fff;border-bottom:1px solid #e7edf2;display:flex;align-items:center;justify-content:space-between;padding:0 clamp(24px,3.3vw,55px)} +.breadcrumb{font-size:12px;color:#8c9bac}.breadcrumb span{padding:0 11px;color:#bbc5d0}.breadcrumb strong{color:#344961;font-weight:700} +.topbar-right{display:flex;align-items:center;gap:19px}.topbar-user{display:flex;align-items:center;gap:9px;color:#34455b;font-size:12px;font-weight:700} +.host-settings-mobile{display:none} +.admin-menu{display:none;position:relative;z-index:11}.admin-menu summary{list-style:none;display:flex;align-items:center;gap:5px;min-height:32px;padding:5px 9px;border-radius:7px;color:#536b7e;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.admin-menu summary::-webkit-details-marker{display:none}.admin-menu summary:hover,.admin-menu[open] summary{background:#edf6f6;color:#117f88}.admin-menu-options{position:absolute;right:0;top:calc(100% + 5px);display:grid;gap:3px;min-width:148px;padding:6px;border:1px solid #dde7ed;border-radius:9px;background:#fff;box-shadow:0 12px 30px rgba(17,42,59,.14)}.admin-menu-options .button{width:100%;justify-content:flex-start} +.avatar{display:inline-flex;align-items:center;justify-content:center;border-radius:50%;height:30px;width:30px;background:#e9f8f7;color:#118e9a;font-size:12px;font-weight:800} +.content{max-width:1600px;margin:0 auto;padding:37px clamp(24px,3.3vw,55px) 24px} +.page-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin-bottom:32px} +.page-heading h1{font-size:28px;letter-spacing:-.6px;margin:9px 0 8px}.page-heading p{margin:0;color:#8390a2;font-size:13px} +.resource-warning{margin:-11px 0 23px;padding:13px 16px;border:1px solid #f0d8aa;border-radius:9px;background:#fff8eb;color:#916323;font-size:12px;line-height:1.65;overflow-wrap:anywhere} +.heading-actions{display:flex;gap:10px;padding-bottom:3px} +.overview-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:17px;margin-bottom:25px} +.stat-card{min-height:148px;padding:22px 24px;background:#fff;border:1px solid #e9eef3;border-radius:13px;box-shadow:0 9px 27px rgba(18,47,71,.025)} +.stat-top{display:flex;align-items:center;justify-content:space-between;color:#79889a;font-size:12px;font-weight:700} +.stat-icon{display:flex;align-items:center;justify-content:center;width:33px;height:33px;border-radius:9px;font-size:16px} +.stat-icon.total{background:#e9f4fb;color:#4387b4}.stat-icon.running{background:#e7f9f1;color:#27b07c}.stat-icon.stopped{background:#f0f1f7;color:#8191a9} +.stat-card>strong{display:block;font-size:32px;line-height:1.1;margin-top:14px;letter-spacing:-1px}.stat-card>small{display:flex;align-items:center;gap:9px;color:#a2acb8;font-size:11px;margin-top:10px}.tiny-dot{width:6px;height:6px;box-shadow:none}.tiny-dot.green{background:#39c78e} +.inventory-panel{background:#fff;border:1px solid #e7ecf2;border-radius:13px;box-shadow:0 10px 30px rgba(19,42,65,.027);min-height:390px} +.panel-heading{display:flex;justify-content:space-between;gap:20px;align-items:center;padding:23px 25px 20px;border-bottom:1px solid #edf1f5} +.panel-heading h2{font-size:17px;letter-spacing:-.2px;margin:0 0 6px}.panel-heading p{color:#9aa6b3;font-size:11px;margin:0} +.panel-tools{display:flex;gap:9px}.search-box{position:relative;display:flex;align-items:center}.search-box>span:first-child{position:absolute;left:12px;color:#9aa8b8;font-size:19px;line-height:1} +.search-box input,.panel-tools select{height:37px;border:1px solid #e0e6ec;border-radius:8px;background:#fff;color:#516075;font-size:12px} +.search-box input{width:220px;padding:0 12px 0 34px}.search-box input::placeholder{color:#a4afbb}.panel-tools select{padding:0 29px 0 11px} +.table-scroll{overflow-x:auto;min-height:100px} +table{border-collapse:collapse;width:100%;min-width:850px}.vm-table{min-width:1060px}.vm-table th,.vm-table td{padding-left:15px;padding-right:15px} +thead{background:#fbfcfe}th{height:47px;text-align:left;font-size:10px;letter-spacing:.05em;color:#9ba8b7;text-transform:uppercase;font-weight:800;padding:0 24px} +th.actions-heading{text-align:right;padding-right:28px} +td{height:83px;border-top:1px solid #edf1f5;padding:15px 24px;font-size:12px;color:#607087} +tbody tr:hover{background:#fcfefe} +.vm-identity{display:flex;align-items:center;gap:12px;min-width:160px}.vm-icon{width:38px;height:38px;border-radius:10px;background:#e9f8f8;color:#239eaa;display:flex;align-items:center;justify-content:center;font-size:19px;flex:none}.vm-name{display:block;color:#25384e;font-size:13px;font-weight:800;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-uuid-row{display:flex;align-items:center;gap:5px;margin-top:6px;max-width:265px}.vm-id{display:block;min-width:0;color:#a6b1bf;font-size:10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-uuid-row .vm-copy-icon{width:21px;min-height:21px;padding:2px}.vm-uuid-row .vm-copy-icon svg{width:13px;height:13px} +.vm-public-ip{display:block;color:#16868f;font-size:10px;font-weight:700;margin-top:5px;white-space:nowrap} +.vm-name-link{display:block;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;padding:2px 0;color:#25384e;font-size:13px;font-weight:800;text-align:left;text-decoration:underline;text-decoration-color:transparent;text-underline-offset:3px;cursor:pointer}.vm-name-link:not(:disabled):hover,.vm-name-link:not(:disabled):focus-visible{color:#118e98;text-decoration-color:currentColor}.vm-metadata{display:block;max-width:205px;color:#53647a;line-height:1.5;overflow-wrap:anywhere}.vm-ip{color:#16868f;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;white-space:nowrap} +.state-pill{display:inline-flex;align-items:center;gap:7px;padding:6px 9px;border-radius:6px;font-size:11px;font-weight:800;background:#f1f3f6;color:#758499;white-space:nowrap}.state-pill:before{content:"";width:6px;height:6px;background:currentColor;border-radius:50%}.state-pill.running{background:#e7f8ef;color:#20a46f}.state-pill.stopped{background:#f2f4f7;color:#8290a3}.state-pill.other{background:#fff4e5;color:#b98129} +.vm-spec{color:#53647a;white-space:nowrap}.vm-spec strong{color:#283a50;font-weight:700}.vm-spec small{display:block;color:#a2aeb9;font-size:10px;margin-top:5px} +.row-actions{display:flex;align-items:center;justify-content:flex-end;gap:5px;white-space:nowrap}.row-button{border:1px solid transparent;background:transparent;color:#577083;border-radius:7px;padding:7px 8px;min-height:31px;font-size:11px;font-weight:700}.row-button:not(:disabled):hover{background:#e8f7f7;color:#117f88}.row-button.primary{background:#e7f7f7;color:#118e98}.row-button.danger{color:#bf6470}.row-button.danger:not(:disabled):hover{background:#fff0f1;color:#ba3a49} +.empty-state{text-align:center;padding:65px 20px 72px}.empty-icon{margin:0 auto 16px;width:54px;height:54px;display:flex;align-items:center;justify-content:center;border-radius:16px;background:#eaf7f7;color:#17a3aa;font-size:28px}.empty-state h3{font-size:16px;color:#34465a;margin:0 0 8px}.empty-state p{font-size:12px;color:#a0aebe;margin:0} +.footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px} +.vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-summary{display:flex;align-items:center;flex-wrap:wrap;gap:5px 18px}.vm-detail-summary span{white-space:nowrap}.vm-detail-summary strong{color:#455a70;font-weight:700;margin-left:4px}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef} +.vm-detail-inline,.vm-ip-copy-row{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.vm-detail-inline{min-height:25px}.vm-detail-secret{font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-mini-button,.vm-copy-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;border:1px solid #d9e9ea;border-radius:6px;background:#f5fbfb;color:#1b8790;font-size:11px;font-weight:700;min-height:25px;padding:3px 7px}.vm-detail-mini-button:not(:disabled):hover,.vm-copy-icon:not(:disabled):hover{background:#e6f6f7;border-color:#b6dcdf}.vm-copy-icon{width:25px;padding:3px}.vm-copy-icon svg{display:block;width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} +.vm-credential-icon{width:30px;min-height:30px}.vm-credential-icon svg{width:17px;height:17px}.vm-credential-icon .vm-eye-slash{visibility:hidden}.vm-credential-icon[aria-pressed="true"] .vm-eye-slash{visibility:visible} +.vm-detail-facts .vm-detail-credential-row{grid-column:1/-1} +.vm-metrics{margin-top:25px}.vm-metrics-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}.vm-metrics-heading h2{font-size:19px;margin:7px 0 6px}.vm-metrics-heading p{font-size:11px;color:#8191a1;line-height:1.6;margin:0}.vm-metrics-range-control{display:flex;align-items:center;gap:9px;flex:none;color:#64768a;font-size:11px;font-weight:700}.vm-metrics-range-control select{height:37px;padding:0 11px;border:1px solid #dbe6ec;border-radius:8px;color:#344e60;background:#fff;font-size:12px;font-weight:700}.vm-metrics-status{margin:0 0 14px;padding:9px 12px;border-radius:8px;background:#eaf7f7;color:#277b82;font-size:11px;line-height:1.5}.vm-metrics-status.warning{background:#fff6e9;color:#946620}.vm-metrics-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-metric-card{min-width:0;padding:20px 21px 16px;border:1px solid #e7ecf2;border-radius:13px;background:#fff;box-shadow:0 10px 30px rgba(19,42,65,.027)}.vm-metric-card-heading{display:flex;align-items:flex-start;gap:11px;min-height:62px}.vm-metric-card-heading>div{min-width:0}.vm-metric-card-heading h3{margin:1px 0 6px;font-size:13px;color:#32485b}.vm-metric-card-heading p{margin:0;color:#60758a;font-size:12px;line-height:1.45;overflow-wrap:anywhere}.vm-metric-icon{display:flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;border-radius:9px;font-size:18px;font-weight:700}.vm-metric-icon.cpu{background:#e8f8f8;color:#0f9eaa}.vm-metric-icon.memory{background:#edf3fb;color:#4781cf}.vm-metric-icon.disk{background:#eef3fa;color:#477dc9}.vm-metric-icon.network{background:#eaf8f2;color:#17a685}.vm-metric-plot{display:flex;align-items:center;justify-content:center;height:205px;margin:8px 0 6px;overflow:hidden}.vm-metric-plot svg{display:block;width:100%;height:100%;font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif}.vm-metric-gridline{stroke:#e5edf2;stroke-width:1;stroke-dasharray:3 4}.vm-metric-axis-label{fill:#9aabb9;font-size:10px}.vm-metric-empty{margin:0;padding:15px;text-align:center;color:#94a2af;font-size:11px;line-height:1.6}.vm-metric-legend{display:flex;align-items:center;flex-wrap:wrap;gap:15px;padding-left:7px;color:#728297;font-size:10px;font-weight:700}.vm-metric-legend span{display:inline-flex;align-items:center;gap:6px}.vm-metric-swatch{display:inline-block;width:16px;height:0;border-top:3px solid #0f9eaa;border-radius:2px}.vm-metric-swatch.cpu{border-color:#0f9eaa}.vm-metric-swatch.memory{border-color:#4781cf}.vm-metric-swatch.memory-total{border-color:#a4b7d7;border-top-style:dashed}.vm-metric-swatch.disk-read{border-color:#477dc9}.vm-metric-swatch.disk-write{border-color:#e59c46}.vm-metric-swatch.network-rx{border-color:#17a685}.vm-metric-swatch.network-tx{border-color:#926ed0}.vm-metrics-footnote{margin:12px 1px 0;color:#9ba8b6;font-size:10px;line-height:1.6} +.modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)} +.modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)} +.modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:26px 29px 18px;border-bottom:1px solid #edf1f5}.modal-header h2{font-size:21px;letter-spacing:-.35px;margin:7px 0 5px}.modal-header p{font-size:12px;color:#95a1af;margin:0}.icon-button{border:0;border-radius:8px;background:transparent;color:#8a98a8;width:31px;height:31px;font-size:23px;line-height:1;display:flex;align-items:center;justify-content:center}.icon-button:hover{background:#f1f5f8;color:#30445a} +.modal-body{padding:23px 29px 25px}.modal-footer{display:flex;justify-content:flex-end;gap:9px;padding:18px 29px;border-top:1px solid #edf1f5} +.workspace-form-page{width:min(100%,900px);margin:0 auto 48px}.workspace-form-back{padding-left:0;margin-bottom:15px;min-height:34px}.workspace-form-heading{margin-bottom:22px}.workspace-form-heading h1{margin-top:8px}.workspace-form-card{overflow:hidden}.workspace-form-body{padding:28px clamp(22px,3vw,36px) 32px}.workspace-form-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:10px;padding:18px clamp(22px,3vw,36px);border-top:1px solid #edf1f5;background:#fbfdfe}.workspace-form-actions .button{min-width:120px}.workspace-form-body>.form-error{margin:18px 0 0} +.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 17px}.field.full{grid-column:1/-1}.field label{display:block}.field label span{color:#dc5965}.field small{display:block;color:#a1adbb;font-size:10px;margin-top:7px;line-height:1.5}.field select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2393a1ae' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:35px} +.create-source-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;border:0;padding:0;margin:0 0 23px;min-width:0}.create-source-picker legend{color:#34445a;font-size:13px;font-weight:700;padding:0;margin-bottom:10px}.create-source-picker label{position:relative;display:block;cursor:pointer}.create-source-picker input{position:absolute;opacity:0;width:1px;height:1px}.create-source-picker label span{display:block;border:1px solid #dce4eb;border-radius:9px;padding:12px 14px;min-height:65px;background:#fff}.create-source-picker input:checked+span{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.create-source-picker input:focus-visible+span{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.create-source-picker strong{display:block;color:#334a5f;font-size:12px}.create-source-picker small{display:block;color:#8999a8;font-size:10px;margin-top:5px} +.template-field-label{display:block;color:#34445a;font-size:13px;font-weight:700;margin-bottom:10px}.template-field-label span{color:#dc5965}.template-catalog{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:14px}.template-catalog-empty{grid-column:1/-1;margin:0;padding:17px;border:1px dashed #cbdbe3;border-radius:10px;background:#f8fbfc;color:#698094;font-size:12px}.template-family-card{min-width:0;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden}.template-family-card[open]{border-color:#46b6ba;box-shadow:0 0 0 2px rgba(20,166,175,.07)}.template-family-summary{display:flex;align-items:center;flex-direction:column;gap:9px;min-height:153px;padding:20px 13px 13px;cursor:pointer;text-align:center;list-style:none}.template-family-summary::-webkit-details-marker{display:none}.template-family-summary:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:-3px}.template-family-summary strong{color:#30465a;font-size:13px}.template-family-icon{display:flex;align-items:center;justify-content:center;width:65px;height:65px;border-radius:17px;background:linear-gradient(145deg,#2a6385,#173d58);color:#fff;font-size:31px;font-weight:800;box-shadow:0 6px 16px rgba(24,68,90,.15)}.template-family-arrow{color:#258f9b;font-size:20px;line-height:1;transition:transform .2s}.template-family-card[open] .template-family-arrow{transform:rotate(180deg)}.template-versions{display:grid;gap:7px;padding:12px;border-top:1px solid #e7edf2;background:#fbfdfd}.template-version-option{width:100%;display:grid;gap:3px;padding:11px 12px;border:1px solid #dee8ed;border-radius:8px;background:#fff;text-align:left;color:#344e60}.template-version-option strong{font-size:12px}.template-version-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)}.template-version-option:hover{border-color:#48b6bd}.template-admin-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);align-items:start;gap:19px}.template-admin-grid .host-card{min-width:0}.template-admin-grid .form-stack .button{align-self:flex-start}.template-field-help{display:block;margin:-16px 0 19px;color:#8b9bab;font-size:11px;line-height:1.55}.template-import-status{margin:0 0 14px;padding:10px 12px;border-radius:8px;background:#edf8f8;color:#317c85;font-size:11px;line-height:1.6}.template-admin-list{display:grid;gap:10px}.template-admin-list>.muted{margin:0}.template-admin-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:9px 11px;align-items:end;padding:14px;border:1px solid #e0e9ee;border-radius:10px;background:#fbfdfd}.template-admin-row-heading{grid-column:1/-1;display:flex;align-items:center;gap:9px;margin-bottom:3px;color:#34495c;font-size:12px}.template-admin-icon{display:flex;align-items:center;justify-content:center;width:27px;height:27px;border-radius:7px;background:#e3f6f3;color:#138d8f;font-weight:800}.template-admin-row label{grid-column:1/-1;margin:0;color:#75899b;font-size:11px;font-weight:700}.template-admin-row input{width:100%;min-width:0;height:37px;padding:0 10px;border:1px solid #dce4eb;border-radius:7px;background:#fff;color:#20364a;font-size:12px}.template-admin-row .button{min-height:37px}.template-admin-row .form-error{grid-column:1/-1;margin:0} +.template-family-icon.system,.template-admin-icon.system{background:transparent;border:0;box-shadow:none;color:inherit;text-shadow:none}.template-system-logo{display:block;width:100%;height:100%;object-fit:contain}.template-version-option{display:flex;align-items:center;justify-content:center;text-align:center}.template-version-option strong{overflow-wrap:anywhere} +.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px} +.vm-auto-public-pool{display:grid;gap:5px;margin:0 0 18px;padding:13px 15px;border:1px solid #cce9e0;border-radius:9px;background:#f0fbf8}.vm-auto-public-pool strong{font-size:12px;color:#217d6e}.vm-auto-public-pool span{font-size:11px;line-height:1.6;color:#5b837a}.vm-cloud-auth-fields{margin-top:18px} +.input-suffix{position:relative}.input-suffix input{padding-right:48px}.input-suffix span{position:absolute;right:13px;top:13px;color:#97a4b2;font-size:12px} +.form-tip{display:flex;gap:10px;background:#f1f9fa;border:1px solid #e1f2f3;border-radius:9px;padding:12px 14px;color:#318b96;margin-top:22px}.form-tip>span{font-size:16px;line-height:1}.form-tip p{font-size:11px;line-height:1.55;margin:0}.modal-body>.form-error{margin:18px 0 0} +.delete-copy{font-size:13px;color:#647388;line-height:1.8;margin:0 0 19px}.delete-copy strong{color:#263c54;overflow-wrap:anywhere}.danger-text{color:#d64753} +.reinstall-warning{margin:0 0 15px;padding:14px 16px;border:1px solid #f2cbd0;border-radius:9px;background:#fff4f5;color:#99414d;font-size:12px;line-height:1.7}.reinstall-warning strong{display:block;margin-bottom:4px;color:#a82f3f;font-size:13px}.reinstall-network{margin:0 0 21px;color:#51677c;font-size:12px;line-height:1.7}.reinstall-network strong{color:#174458;overflow-wrap:anywhere} +.reinstall-progress{display:flex;align-items:flex-start;gap:15px;padding:14px 2px;min-height:105px}.reinstall-progress .console-spinner{flex:none;margin-top:2px}.reinstall-progress strong{display:block;color:#274459;font-size:14px}.reinstall-progress p{margin:8px 0;color:#238894;font-size:12px;line-height:1.6}.reinstall-progress small{display:block;color:#8192a4;font-size:11px;line-height:1.6} +.reinstall-result{padding:4px 0 10px}.reinstall-result h3{margin:0 0 10px;color:#167f72;font-size:18px}.reinstall-result.failed h3{color:#b1404c}.reinstall-result.unknown h3{color:#916425}.reinstall-result>p{margin:0 0 14px;color:#4f6478;font-size:12px;line-height:1.75;overflow-wrap:anywhere}.reinstall-password-box{border:1px solid #b9e2d5;border-radius:9px;background:#f1fbf7;padding:14px;margin-top:15px}.reinstall-password-box>span{display:block;color:#286f60;font-size:12px;font-weight:700}.reinstall-password-box>div{display:flex;align-items:center;gap:9px;margin:10px 0}.reinstall-password-box code{display:block;flex:1;min-width:0;padding:11px;border-radius:7px;background:#fff;color:#1d4a41;font-size:14px;overflow-wrap:anywhere;user-select:all}.reinstall-password-box small{display:block;color:#617f76;font-size:11px;line-height:1.6}.reinstall-result-warning{padding:10px 12px;border-radius:8px;background:#fff6e7;color:#916425!important} +.checkbox-row{border:1px solid #f0dadd;background:#fffafa;border-radius:9px;padding:14px;display:flex;align-items:flex-start;gap:11px;cursor:pointer}.checkbox-row input{margin:3px 0 0;accent-color:#d94350}.checkbox-row strong{display:block;font-size:12px;color:#9e3440}.checkbox-row small{display:block;margin-top:4px;font-size:11px;line-height:1.5;color:#bd7a81} +.console-backdrop{padding:24px}.console-modal{width:min(100%,1200px);max-height:95vh;display:flex;flex-direction:column;overflow:hidden;background:#101820}.console-toolbar{display:flex;align-items:center;justify-content:space-between;gap:20px;background:#fff;padding:15px 20px}.console-toolbar h2{margin:4px 0 1px;font-size:16px}.console-toolbar p{margin:0;font-size:11px;color:#93a1af}.console-tools{display:flex;align-items:center;gap:8px}.console-stage{position:relative;min-height:280px;height:min(70vh,720px);background:#101820;display:flex;align-items:center;justify-content:center;overflow:hidden}.console-stage canvas{max-width:100%;max-height:100%}.console-placeholder{display:flex;align-items:center;gap:13px;color:#a9b9c5;font-size:12px}.console-spinner{height:20px;width:20px;border-radius:50%;border:2px solid #4f6673;border-top-color:#40ccd0;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.console-password{display:flex;align-items:center;gap:10px;background:#fff;padding:13px 20px}.console-password label{margin:0;white-space:nowrap}.console-password input{width:220px;height:35px} +.toast-region{position:fixed;right:23px;bottom:22px;display:flex;flex-direction:column;gap:9px;z-index:80;pointer-events:none}.toast{max-width:min(430px,calc(100vw - 36px));padding:12px 16px;border-radius:9px;color:#fff;background:#20364a;box-shadow:0 10px 24px rgba(15,30,44,.2);font-size:12px;line-height:1.5;pointer-events:auto}.toast.error{background:#ae3c49}.toast.success{background:#157e75} +@media(max-width:1150px){th,td{padding-left:15px;padding-right:15px}.row-button{padding:6px}.content{padding-left:28px;padding-right:28px}} +@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.admin-menu{display:block}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}} +@media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}} +@media(max-width:960px){.update-grid{grid-template-columns:1fr}} +@media(max-width:960px){.template-admin-grid{grid-template-columns:1fr}} +@media(max-width:960px){.ssh-keys-grid{grid-template-columns:1fr}} +@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}} +@media(max-width:740px){.vm-metrics-grid{grid-template-columns:1fr}.vm-metrics-heading{align-items:flex-start;flex-direction:column}.vm-metric-plot{height:190px}} +@media(max-width:740px){.login-layout{display:block;min-height:100vh}.login-art{display:none}.login-form-side{min-height:100vh;padding:32px 25px}.login-mobile-brand{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:800;margin-bottom:70px}.login-card h2{font-size:29px}.page-heading{align-items:flex-start;flex-direction:column;gap:20px}.heading-actions{width:100%}.heading-actions .button{flex:1}.overview-grid{gap:9px}.stat-card{min-height:121px;padding:16px}.stat-card>strong{font-size:25px}.stat-top{font-size:10px}.stat-icon{width:27px;height:27px;font-size:12px}.stat-card>small{font-size:9px}.panel-heading{align-items:flex-start;flex-direction:column;padding:19px}.panel-tools{width:100%}.search-box{flex:1}.search-box input{width:100%}.footer-note{text-align:left}.console-toolbar{align-items:flex-start}.console-tools{flex-wrap:wrap;justify-content:flex-end}.console-tools .button{font-size:10px}} +@media(max-width:740px){.vm-table{min-width:0}.vm-table thead{display:none}.vm-table tbody{display:grid;gap:12px;padding:12px}.vm-table tr{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid #e4ebf0;border-radius:10px;overflow:hidden}.vm-table td{display:block;min-width:0;height:auto;border:0;padding:12px 14px}.vm-table td:first-child{grid-column:1/-1;border-bottom:1px solid #edf1f5}.vm-table td:not(:first-child):before{content:attr(data-label);display:block;color:#9ba8b7;font-size:10px;font-weight:800;margin-bottom:7px}.vm-table .vm-metadata{max-width:none}.vm-table .vm-ip{white-space:normal}.vm-detail-facts{padding:4px 17px 12px}.vm-detail-actions{padding:16px 19px 19px}} +@media(max-width:740px){.setup-layout{display:block}.setup-intro{min-height:0;padding:28px 25px}.setup-brand{margin:0 0 38px}.setup-intro h1{font-size:31px;margin:11px 0}.setup-intro p{font-size:12px;margin-bottom:24px}.setup-steps{margin-top:0}.setup-form-side{padding:36px 25px 55px}.setup-card h2{font-size:27px}.host-side-stack{grid-template-columns:1fr}.host-heading{align-items:flex-start;flex-direction:column}.host-topbar{height:65px}.host-content{padding-top:27px}.host-card{padding:20px}} +@media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}} +@media(max-width:510px){.topbar-right{flex-wrap:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.update-versions{grid-template-columns:1fr}} +@media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.template-catalog{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.template-family-summary{min-height:137px;padding:16px 9px 11px}.template-family-icon{width:55px;height:55px;font-size:27px}.template-versions{padding:8px}.template-version-option{padding:9px 8px}.template-admin-row{grid-template-columns:1fr}.template-admin-row .button{justify-self:start}} +@media(max-width:510px){.workspace-form-body{padding:22px 19px 25px}.workspace-form-actions{padding:15px 19px}.workspace-form-actions .button{flex:1 1 100%}.workspace-form-back{margin-bottom:10px}} +@media(max-width:510px){.host-public-pool>.form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.ssh-key-row{align-items:flex-start;flex-direction:column}.ssh-key-actions{width:100%}.ssh-key-actions .button{flex:1}} +@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}} +.rescue-status{margin:8px 0 17px;padding:12px 14px;border:1px solid #c8e9e8;border-radius:9px;background:#f0fbfa;color:#236d71;font-size:12px;line-height:1.6} +.rescue-directory-note{margin:0 0 17px;padding:10px 12px;border:1px solid #d6e8ee;border-radius:8px;background:#f6fafc;color:#557085;font-size:11px;line-height:1.6;overflow-wrap:anywhere} +.rescue-login-note{margin:0 0 19px;color:#557085;font-size:12px;line-height:1.7} +#rescue-status-title{margin:0;color:#2c465a;font-size:16px} +.rescue-template-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin:0 0 21px} +.rescue-template-card{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;min-height:130px;padding:16px 13px;border:1px solid #dce7ec;border-radius:11px;background:#fff;color:#314b5c;text-align:center;cursor:pointer;overflow-wrap:anywhere} +.rescue-template-card:hover,.rescue-template-card:focus-visible{border-color:#38aeb7;outline:none;box-shadow:0 0 0 3px rgba(25,179,187,.1)} +.rescue-template-card[aria-pressed="true"]{border-color:#28a8b0;background:#eaf8f8;box-shadow:0 0 0 2px rgba(25,179,187,.12)} +.rescue-template-card:disabled{cursor:wait;opacity:.7} +.rescue-template-symbol{display:grid;place-items:center;width:43px;height:43px;border-radius:10px;background:#e2f6f5;color:#168d94;font-size:24px;font-weight:800} +.rescue-template-card strong{font-size:12px}.rescue-template-card small{font-size:11px;color:#8798a5} +.rescue-actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:12px}.rescue-actions .button{min-width:190px} +.rescue-template-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 14px;border:1px solid #e0e9ee;border-radius:9px;background:#fbfdfd} +.rescue-template-row-label{display:grid;gap:5px;min-width:0;overflow-wrap:anywhere}.rescue-template-row-label strong{font-size:12px;color:#34495c}.rescue-template-row-label small{font-size:11px;color:#8a9caa} +#rescue-template-file{height:auto;padding:10px 12px} +@media(max-width:510px){.rescue-template-cards{grid-template-columns:repeat(2,minmax(0,1fr))}.rescue-actions .button{width:100%}.rescue-template-row{align-items:flex-start;flex-direction:column}} diff --git a/engine/static/ubuntu-icon.svg b/engine/static/ubuntu-icon.svg new file mode 100644 index 00000000..89b79e94 --- /dev/null +++ b/engine/static/ubuntu-icon.svg @@ -0,0 +1 @@ + diff --git a/engine/static/vendor/novnc/LICENSE.txt b/engine/static/vendor/novnc/LICENSE.txt new file mode 100644 index 00000000..0581c11e --- /dev/null +++ b/engine/static/vendor/novnc/LICENSE.txt @@ -0,0 +1,62 @@ +noVNC is Copyright (C) 2022 The noVNC authors +(./AUTHORS) + +The noVNC core library files are licensed under the MPL 2.0 (Mozilla +Public License 2.0). The noVNC core library is composed of the +Javascript code necessary for full noVNC operation. This includes (but +is not limited to): + + core/**/*.js + app/*.js + test/playback.js + +The HTML, CSS, font and images files that included with the noVNC +source distibution (or repository) are not considered part of the +noVNC core library and are licensed under more permissive licenses. +The intent is to allow easy integration of noVNC into existing web +sites and web applications. + +The HTML, CSS, font and image files are licensed as follows: + + *.html : 2-Clause BSD license + + app/styles/*.css : 2-Clause BSD license + + app/styles/Orbitron* : SIL Open Font License 1.1 + (Copyright 2009 Matt McInerney) + + app/images/ : Creative Commons Attribution-ShareAlike + http://creativecommons.org/licenses/by-sa/3.0/ + +Some portions of noVNC are copyright to their individual authors. +Please refer to the individual source files and/or to the noVNC commit +history: https://github.com/novnc/noVNC/commits/master + +The are several files and projects that have been incorporated into +the noVNC core library. Here is a list of those files and the original +licenses (all MPL 2.0 compatible): + + core/base64.js : MPL 2.0 + + core/des.js : Various BSD style licenses + + vendor/pako/ : MIT + +Any other files not mentioned above are typically marked with +a copyright/license header at the top of the file. The default noVNC +license is MPL-2.0. + +The following license texts are included: + + docs/LICENSE.MPL-2.0 + docs/LICENSE.OFL-1.1 + docs/LICENSE.BSD-3-Clause (New BSD) + docs/LICENSE.BSD-2-Clause (Simplified BSD / FreeBSD) + vendor/pako/LICENSE (MIT) + +Or alternatively the license texts may be found here: + + http://www.mozilla.org/MPL/2.0/ + http://scripts.sil.org/OFL + http://en.wikipedia.org/wiki/BSD_licenses + https://opensource.org/licenses/MIT diff --git a/engine/static/vendor/novnc/core/base64.js b/engine/static/vendor/novnc/core/base64.js new file mode 100644 index 00000000..db572c2d --- /dev/null +++ b/engine/static/vendor/novnc/core/base64.js @@ -0,0 +1,104 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// From: http://hg.mozilla.org/mozilla-central/raw-file/ec10630b1a54/js/src/devtools/jint/sunspider/string-base64.js + +import * as Log from './util/logging.js'; + +export default { + /* Convert data (an array of integers) to a Base64 string. */ + toBase64Table: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''), + base64Pad: '=', + + encode(data) { + "use strict"; + let result = ''; + const length = data.length; + const lengthpad = (length % 3); + // Convert every three bytes to 4 ascii characters. + + for (let i = 0; i < (length - 2); i += 3) { + result += this.toBase64Table[data[i] >> 2]; + result += this.toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)]; + result += this.toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)]; + result += this.toBase64Table[data[i + 2] & 0x3f]; + } + + // Convert the remaining 1 or 2 bytes, pad out to 4 characters. + const j = length - lengthpad; + if (lengthpad === 2) { + result += this.toBase64Table[data[j] >> 2]; + result += this.toBase64Table[((data[j] & 0x03) << 4) + (data[j + 1] >> 4)]; + result += this.toBase64Table[(data[j + 1] & 0x0f) << 2]; + result += this.toBase64Table[64]; + } else if (lengthpad === 1) { + result += this.toBase64Table[data[j] >> 2]; + result += this.toBase64Table[(data[j] & 0x03) << 4]; + result += this.toBase64Table[64]; + result += this.toBase64Table[64]; + } + + return result; + }, + + /* Convert Base64 data to a string */ + /* eslint-disable comma-spacing */ + toBinaryTable: [ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 + ], + /* eslint-enable comma-spacing */ + + decode(data, offset = 0) { + let dataLength = data.indexOf('=') - offset; + if (dataLength < 0) { dataLength = data.length - offset; } + + /* Every four characters is 3 resulting numbers */ + const resultLength = (dataLength >> 2) * 3 + Math.floor((dataLength % 4) / 1.5); + const result = new Array(resultLength); + + // Convert one by one. + + let leftbits = 0; // number of bits decoded, but yet to be appended + let leftdata = 0; // bits decoded, but yet to be appended + for (let idx = 0, i = offset; i < data.length; i++) { + const c = this.toBinaryTable[data.charCodeAt(i) & 0x7f]; + const padding = (data.charAt(i) === this.base64Pad); + // Skip illegal characters and whitespace + if (c === -1) { + Log.Error("Illegal character code " + data.charCodeAt(i) + " at position " + i); + continue; + } + + // Collect data into leftdata, update bitcount + leftdata = (leftdata << 6) | c; + leftbits += 6; + + // If we have 8 or more bits, append 8 bits to the result + if (leftbits >= 8) { + leftbits -= 8; + // Append if not padding. + if (!padding) { + result[idx++] = (leftdata >> leftbits) & 0xff; + } + leftdata &= (1 << leftbits) - 1; + } + } + + // If there are any bits left, the base64 string was corrupted + if (leftbits) { + const err = new Error('Corrupted base64 string'); + err.name = 'Base64-Error'; + throw err; + } + + return result; + } +}; /* End of Base64 namespace */ diff --git a/engine/static/vendor/novnc/core/crypto/aes.js b/engine/static/vendor/novnc/core/crypto/aes.js new file mode 100644 index 00000000..e6aaea7c --- /dev/null +++ b/engine/static/vendor/novnc/core/crypto/aes.js @@ -0,0 +1,178 @@ +export class AESECBCipher { + constructor() { + this._key = null; + } + + get algorithm() { + return { name: "AES-ECB" }; + } + + static async importKey(key, _algorithm, extractable, keyUsages) { + const cipher = new AESECBCipher; + await cipher._importKey(key, extractable, keyUsages); + return cipher; + } + + async _importKey(key, extractable, keyUsages) { + this._key = await window.crypto.subtle.importKey( + "raw", key, {name: "AES-CBC"}, extractable, keyUsages); + } + + async encrypt(_algorithm, plaintext) { + const x = new Uint8Array(plaintext); + if (x.length % 16 !== 0 || this._key === null) { + return null; + } + const n = x.length / 16; + for (let i = 0; i < n; i++) { + const y = new Uint8Array(await window.crypto.subtle.encrypt({ + name: "AES-CBC", + iv: new Uint8Array(16), + }, this._key, x.slice(i * 16, i * 16 + 16))).slice(0, 16); + x.set(y, i * 16); + } + return x; + } +} + +export class AESEAXCipher { + constructor() { + this._rawKey = null; + this._ctrKey = null; + this._cbcKey = null; + this._zeroBlock = new Uint8Array(16); + this._prefixBlock0 = this._zeroBlock; + this._prefixBlock1 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + this._prefixBlock2 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]); + } + + get algorithm() { + return { name: "AES-EAX" }; + } + + async _encryptBlock(block) { + const encrypted = await window.crypto.subtle.encrypt({ + name: "AES-CBC", + iv: this._zeroBlock, + }, this._cbcKey, block); + return new Uint8Array(encrypted).slice(0, 16); + } + + async _initCMAC() { + const k1 = await this._encryptBlock(this._zeroBlock); + const k2 = new Uint8Array(16); + const v = k1[0] >>> 6; + for (let i = 0; i < 15; i++) { + k2[i] = (k1[i + 1] >> 6) | (k1[i] << 2); + k1[i] = (k1[i + 1] >> 7) | (k1[i] << 1); + } + const lut = [0x0, 0x87, 0x0e, 0x89]; + k2[14] ^= v >>> 1; + k2[15] = (k1[15] << 2) ^ lut[v]; + k1[15] = (k1[15] << 1) ^ lut[v >> 1]; + this._k1 = k1; + this._k2 = k2; + } + + async _encryptCTR(data, counter) { + const encrypted = await window.crypto.subtle.encrypt({ + name: "AES-CTR", + counter: counter, + length: 128 + }, this._ctrKey, data); + return new Uint8Array(encrypted); + } + + async _decryptCTR(data, counter) { + const decrypted = await window.crypto.subtle.decrypt({ + name: "AES-CTR", + counter: counter, + length: 128 + }, this._ctrKey, data); + return new Uint8Array(decrypted); + } + + async _computeCMAC(data, prefixBlock) { + if (prefixBlock.length !== 16) { + return null; + } + const n = Math.floor(data.length / 16); + const m = Math.ceil(data.length / 16); + const r = data.length - n * 16; + const cbcData = new Uint8Array((m + 1) * 16); + cbcData.set(prefixBlock); + cbcData.set(data, 16); + if (r === 0) { + for (let i = 0; i < 16; i++) { + cbcData[n * 16 + i] ^= this._k1[i]; + } + } else { + cbcData[(n + 1) * 16 + r] = 0x80; + for (let i = 0; i < 16; i++) { + cbcData[(n + 1) * 16 + i] ^= this._k2[i]; + } + } + let cbcEncrypted = await window.crypto.subtle.encrypt({ + name: "AES-CBC", + iv: this._zeroBlock, + }, this._cbcKey, cbcData); + + cbcEncrypted = new Uint8Array(cbcEncrypted); + const mac = cbcEncrypted.slice(cbcEncrypted.length - 32, cbcEncrypted.length - 16); + return mac; + } + + static async importKey(key, _algorithm, _extractable, _keyUsages) { + const cipher = new AESEAXCipher; + await cipher._importKey(key); + return cipher; + } + + async _importKey(key) { + this._rawKey = key; + this._ctrKey = await window.crypto.subtle.importKey( + "raw", key, {name: "AES-CTR"}, false, ["encrypt", "decrypt"]); + this._cbcKey = await window.crypto.subtle.importKey( + "raw", key, {name: "AES-CBC"}, false, ["encrypt"]); + await this._initCMAC(); + } + + async encrypt(algorithm, message) { + const ad = algorithm.additionalData; + const nonce = algorithm.iv; + const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0); + const encrypted = await this._encryptCTR(message, nCMAC); + const adCMAC = await this._computeCMAC(ad, this._prefixBlock1); + const mac = await this._computeCMAC(encrypted, this._prefixBlock2); + for (let i = 0; i < 16; i++) { + mac[i] ^= nCMAC[i] ^ adCMAC[i]; + } + const res = new Uint8Array(16 + encrypted.length); + res.set(encrypted); + res.set(mac, encrypted.length); + return res; + } + + async decrypt(algorithm, data) { + const encrypted = data.slice(0, data.length - 16); + const ad = algorithm.additionalData; + const nonce = algorithm.iv; + const mac = data.slice(data.length - 16); + const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0); + const adCMAC = await this._computeCMAC(ad, this._prefixBlock1); + const computedMac = await this._computeCMAC(encrypted, this._prefixBlock2); + for (let i = 0; i < 16; i++) { + computedMac[i] ^= nCMAC[i] ^ adCMAC[i]; + } + if (computedMac.length !== mac.length) { + return null; + } + for (let i = 0; i < mac.length; i++) { + if (computedMac[i] !== mac[i]) { + return null; + } + } + const res = await this._decryptCTR(encrypted, nCMAC); + return res; + } +} diff --git a/engine/static/vendor/novnc/core/crypto/bigint.js b/engine/static/vendor/novnc/core/crypto/bigint.js new file mode 100644 index 00000000..d3443265 --- /dev/null +++ b/engine/static/vendor/novnc/core/crypto/bigint.js @@ -0,0 +1,34 @@ +export function modPow(b, e, m) { + let r = 1n; + b = b % m; + while (e > 0n) { + if ((e & 1n) === 1n) { + r = (r * b) % m; + } + e = e >> 1n; + b = (b * b) % m; + } + return r; +} + +export function bigIntToU8Array(bigint, padLength=0) { + let hex = bigint.toString(16); + if (padLength === 0) { + padLength = Math.ceil(hex.length / 2); + } + hex = hex.padStart(padLength * 2, '0'); + const length = hex.length / 2; + const arr = new Uint8Array(length); + for (let i = 0; i < length; i++) { + arr[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); + } + return arr; +} + +export function u8ArrayToBigInt(arr) { + let hex = '0x'; + for (let i = 0; i < arr.length; i++) { + hex += arr[i].toString(16).padStart(2, '0'); + } + return BigInt(hex); +} diff --git a/engine/static/vendor/novnc/core/crypto/crypto.js b/engine/static/vendor/novnc/core/crypto/crypto.js new file mode 100644 index 00000000..cc17da22 --- /dev/null +++ b/engine/static/vendor/novnc/core/crypto/crypto.js @@ -0,0 +1,90 @@ +import { AESECBCipher, AESEAXCipher } from "./aes.js"; +import { DESCBCCipher, DESECBCipher } from "./des.js"; +import { RSACipher } from "./rsa.js"; +import { DHCipher } from "./dh.js"; +import { MD5 } from "./md5.js"; + +// A single interface for the cryptographic algorithms not supported by SubtleCrypto. +// Both synchronous and asynchronous implmentations are allowed. +class LegacyCrypto { + constructor() { + this._algorithms = { + "AES-ECB": AESECBCipher, + "AES-EAX": AESEAXCipher, + "DES-ECB": DESECBCipher, + "DES-CBC": DESCBCCipher, + "RSA-PKCS1-v1_5": RSACipher, + "DH": DHCipher, + "MD5": MD5, + }; + } + + encrypt(algorithm, key, data) { + if (key.algorithm.name !== algorithm.name) { + throw new Error("algorithm does not match"); + } + if (typeof key.encrypt !== "function") { + throw new Error("key does not support encryption"); + } + return key.encrypt(algorithm, data); + } + + decrypt(algorithm, key, data) { + if (key.algorithm.name !== algorithm.name) { + throw new Error("algorithm does not match"); + } + if (typeof key.decrypt !== "function") { + throw new Error("key does not support encryption"); + } + return key.decrypt(algorithm, data); + } + + importKey(format, keyData, algorithm, extractable, keyUsages) { + if (format !== "raw") { + throw new Error("key format is not supported"); + } + const alg = this._algorithms[algorithm.name]; + if (typeof alg === "undefined" || typeof alg.importKey !== "function") { + throw new Error("algorithm is not supported"); + } + return alg.importKey(keyData, algorithm, extractable, keyUsages); + } + + generateKey(algorithm, extractable, keyUsages) { + const alg = this._algorithms[algorithm.name]; + if (typeof alg === "undefined" || typeof alg.generateKey !== "function") { + throw new Error("algorithm is not supported"); + } + return alg.generateKey(algorithm, extractable, keyUsages); + } + + exportKey(format, key) { + if (format !== "raw") { + throw new Error("key format is not supported"); + } + if (typeof key.exportKey !== "function") { + throw new Error("key does not support exportKey"); + } + return key.exportKey(); + } + + digest(algorithm, data) { + const alg = this._algorithms[algorithm]; + if (typeof alg !== "function") { + throw new Error("algorithm is not supported"); + } + return alg(data); + } + + deriveBits(algorithm, key, length) { + if (key.algorithm.name !== algorithm.name) { + throw new Error("algorithm does not match"); + } + if (typeof key.deriveBits !== "function") { + throw new Error("key does not support deriveBits"); + } + return key.deriveBits(algorithm, length); + } +} + +export default new LegacyCrypto; diff --git a/engine/static/vendor/novnc/core/crypto/des.js b/engine/static/vendor/novnc/core/crypto/des.js new file mode 100644 index 00000000..8dab31fb --- /dev/null +++ b/engine/static/vendor/novnc/core/crypto/des.js @@ -0,0 +1,330 @@ +/* + * Ported from Flashlight VNC ActionScript implementation: + * http://www.wizhelp.com/flashlight-vnc/ + * + * Full attribution follows: + * + * ------------------------------------------------------------------------- + * + * This DES class has been extracted from package Acme.Crypto for use in VNC. + * The unnecessary odd parity code has been removed. + * + * These changes are: + * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. + * + * This software 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. + * + + * DesCipher - the DES encryption method + * + * The meat of this code is by Dave Zimmerman , and is: + * + * Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved. + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and + * without fee is hereby granted, provided that this copyright notice is kept + * intact. + * + * WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY + * OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED + * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE + * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. + * + * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE + * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE + * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT + * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE + * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE + * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP + * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR + * HIGH RISK ACTIVITIES. + * + * + * The rest is: + * + * Copyright (C) 1996 by Jef Poskanzer . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * Visit the ACME Labs Java page for up-to-date versions of this and other + * fine Java utilities: http://www.acme.com/java/ + */ + +/* eslint-disable comma-spacing */ + +// Tables, permutations, S-boxes, etc. +const PC2 = [13,16,10,23, 0, 4, 2,27,14, 5,20, 9,22,18,11, 3, + 25, 7,15, 6,26,19,12, 1,40,51,30,36,46,54,29,39, + 50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31 ], + totrot = [ 1, 2, 4, 6, 8,10,12,14,15,17,19,21,23,25,27,28]; + +const z = 0x0; +let a,b,c,d,e,f; +a=1<<16; b=1<<24; c=a|b; d=1<<2; e=1<<10; f=d|e; +const SP1 = [c|e,z|z,a|z,c|f,c|d,a|f,z|d,a|z,z|e,c|e,c|f,z|e,b|f,c|d,b|z,z|d, + z|f,b|e,b|e,a|e,a|e,c|z,c|z,b|f,a|d,b|d,b|d,a|d,z|z,z|f,a|f,b|z, + a|z,c|f,z|d,c|z,c|e,b|z,b|z,z|e,c|d,a|z,a|e,b|d,z|e,z|d,b|f,a|f, + c|f,a|d,c|z,b|f,b|d,z|f,a|f,c|e,z|f,b|e,b|e,z|z,a|d,a|e,z|z,c|d]; +a=1<<20; b=1<<31; c=a|b; d=1<<5; e=1<<15; f=d|e; +const SP2 = [c|f,b|e,z|e,a|f,a|z,z|d,c|d,b|f,b|d,c|f,c|e,b|z,b|e,a|z,z|d,c|d, + a|e,a|d,b|f,z|z,b|z,z|e,a|f,c|z,a|d,b|d,z|z,a|e,z|f,c|e,c|z,z|f, + z|z,a|f,c|d,a|z,b|f,c|z,c|e,z|e,c|z,b|e,z|d,c|f,a|f,z|d,z|e,b|z, + z|f,c|e,a|z,b|d,a|d,b|f,b|d,a|d,a|e,z|z,b|e,z|f,b|z,c|d,c|f,a|e]; +a=1<<17; b=1<<27; c=a|b; d=1<<3; e=1<<9; f=d|e; +const SP3 = [z|f,c|e,z|z,c|d,b|e,z|z,a|f,b|e,a|d,b|d,b|d,a|z,c|f,a|d,c|z,z|f, + b|z,z|d,c|e,z|e,a|e,c|z,c|d,a|f,b|f,a|e,a|z,b|f,z|d,c|f,z|e,b|z, + c|e,b|z,a|d,z|f,a|z,c|e,b|e,z|z,z|e,a|d,c|f,b|e,b|d,z|e,z|z,c|d, + b|f,a|z,b|z,c|f,z|d,a|f,a|e,b|d,c|z,b|f,z|f,c|z,a|f,z|d,c|d,a|e]; +a=1<<13; b=1<<23; c=a|b; d=1<<0; e=1<<7; f=d|e; +const SP4 = [c|d,a|f,a|f,z|e,c|e,b|f,b|d,a|d,z|z,c|z,c|z,c|f,z|f,z|z,b|e,b|d, + z|d,a|z,b|z,c|d,z|e,b|z,a|d,a|e,b|f,z|d,a|e,b|e,a|z,c|e,c|f,z|f, + b|e,b|d,c|z,c|f,z|f,z|z,z|z,c|z,a|e,b|e,b|f,z|d,c|d,a|f,a|f,z|e, + c|f,z|f,z|d,a|z,b|d,a|d,c|e,b|f,a|d,a|e,b|z,c|d,z|e,b|z,a|z,c|e]; +a=1<<25; b=1<<30; c=a|b; d=1<<8; e=1<<19; f=d|e; +const SP5 = [z|d,a|f,a|e,c|d,z|e,z|d,b|z,a|e,b|f,z|e,a|d,b|f,c|d,c|e,z|f,b|z, + a|z,b|e,b|e,z|z,b|d,c|f,c|f,a|d,c|e,b|d,z|z,c|z,a|f,a|z,c|z,z|f, + z|e,c|d,z|d,a|z,b|z,a|e,c|d,b|f,a|d,b|z,c|e,a|f,b|f,z|d,a|z,c|e, + c|f,z|f,c|z,c|f,a|e,z|z,b|e,c|z,z|f,a|d,b|d,z|e,z|z,b|e,a|f,b|d]; +a=1<<22; b=1<<29; c=a|b; d=1<<4; e=1<<14; f=d|e; +const SP6 = [b|d,c|z,z|e,c|f,c|z,z|d,c|f,a|z,b|e,a|f,a|z,b|d,a|d,b|e,b|z,z|f, + z|z,a|d,b|f,z|e,a|e,b|f,z|d,c|d,c|d,z|z,a|f,c|e,z|f,a|e,c|e,b|z, + b|e,z|d,c|d,a|e,c|f,a|z,z|f,b|d,a|z,b|e,b|z,z|f,b|d,c|f,a|e,c|z, + a|f,c|e,z|z,c|d,z|d,z|e,c|z,a|f,z|e,a|d,b|f,z|z,c|e,b|z,a|d,b|f]; +a=1<<21; b=1<<26; c=a|b; d=1<<1; e=1<<11; f=d|e; +const SP7 = [a|z,c|d,b|f,z|z,z|e,b|f,a|f,c|e,c|f,a|z,z|z,b|d,z|d,b|z,c|d,z|f, + b|e,a|f,a|d,b|e,b|d,c|z,c|e,a|d,c|z,z|e,z|f,c|f,a|e,z|d,b|z,a|e, + b|z,a|e,a|z,b|f,b|f,c|d,c|d,z|d,a|d,b|z,b|e,a|z,c|e,z|f,a|f,c|e, + z|f,b|d,c|f,c|z,a|e,z|z,z|d,c|f,z|z,a|f,c|z,z|e,b|d,b|e,z|e,a|d]; +a=1<<18; b=1<<28; c=a|b; d=1<<6; e=1<<12; f=d|e; +const SP8 = [b|f,z|e,a|z,c|f,b|z,b|f,z|d,b|z,a|d,c|z,c|f,a|e,c|e,a|f,z|e,z|d, + c|z,b|d,b|e,z|f,a|e,a|d,c|d,c|e,z|f,z|z,z|z,c|d,b|d,b|e,a|f,a|z, + a|f,a|z,c|e,z|e,z|d,c|d,z|e,a|f,b|e,z|d,b|d,c|z,c|d,b|z,a|z,b|f, + z|z,c|f,a|d,b|d,c|z,b|e,b|f,z|z,c|f,a|e,a|e,z|f,z|f,a|d,b|z,c|e]; + +/* eslint-enable comma-spacing */ + +class DES { + constructor(password) { + this.keys = []; + + // Set the key. + const pc1m = [], pcr = [], kn = []; + + for (let j = 0, l = 56; j < 56; ++j, l -= 8) { + l += l < -5 ? 65 : l < -3 ? 31 : l < -1 ? 63 : l === 27 ? 35 : 0; // PC1 + const m = l & 0x7; + pc1m[j] = ((password[l >>> 3] & (1<>> 10; + this.keys[KnLi] |= (raw1 & 0x00000fc0) >>> 6; + ++KnLi; + this.keys[KnLi] = (raw0 & 0x0003f000) << 12; + this.keys[KnLi] |= (raw0 & 0x0000003f) << 16; + this.keys[KnLi] |= (raw1 & 0x0003f000) >>> 4; + this.keys[KnLi] |= (raw1 & 0x0000003f); + ++KnLi; + } + } + + // Encrypt 8 bytes of text + enc8(text) { + const b = text.slice(); + let i = 0, l, r, x; // left, right, accumulator + + // Squash 8 bytes to 2 ints + l = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++]; + r = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++]; + + x = ((l >>> 4) ^ r) & 0x0f0f0f0f; + r ^= x; + l ^= (x << 4); + x = ((l >>> 16) ^ r) & 0x0000ffff; + r ^= x; + l ^= (x << 16); + x = ((r >>> 2) ^ l) & 0x33333333; + l ^= x; + r ^= (x << 2); + x = ((r >>> 8) ^ l) & 0x00ff00ff; + l ^= x; + r ^= (x << 8); + r = (r << 1) | ((r >>> 31) & 1); + x = (l ^ r) & 0xaaaaaaaa; + l ^= x; + r ^= x; + l = (l << 1) | ((l >>> 31) & 1); + + for (let i = 0, keysi = 0; i < 8; ++i) { + x = (r << 28) | (r >>> 4); + x ^= this.keys[keysi++]; + let fval = SP7[x & 0x3f]; + fval |= SP5[(x >>> 8) & 0x3f]; + fval |= SP3[(x >>> 16) & 0x3f]; + fval |= SP1[(x >>> 24) & 0x3f]; + x = r ^ this.keys[keysi++]; + fval |= SP8[x & 0x3f]; + fval |= SP6[(x >>> 8) & 0x3f]; + fval |= SP4[(x >>> 16) & 0x3f]; + fval |= SP2[(x >>> 24) & 0x3f]; + l ^= fval; + x = (l << 28) | (l >>> 4); + x ^= this.keys[keysi++]; + fval = SP7[x & 0x3f]; + fval |= SP5[(x >>> 8) & 0x3f]; + fval |= SP3[(x >>> 16) & 0x3f]; + fval |= SP1[(x >>> 24) & 0x3f]; + x = l ^ this.keys[keysi++]; + fval |= SP8[x & 0x0000003f]; + fval |= SP6[(x >>> 8) & 0x3f]; + fval |= SP4[(x >>> 16) & 0x3f]; + fval |= SP2[(x >>> 24) & 0x3f]; + r ^= fval; + } + + r = (r << 31) | (r >>> 1); + x = (l ^ r) & 0xaaaaaaaa; + l ^= x; + r ^= x; + l = (l << 31) | (l >>> 1); + x = ((l >>> 8) ^ r) & 0x00ff00ff; + r ^= x; + l ^= (x << 8); + x = ((l >>> 2) ^ r) & 0x33333333; + r ^= x; + l ^= (x << 2); + x = ((r >>> 16) ^ l) & 0x0000ffff; + l ^= x; + r ^= (x << 16); + x = ((r >>> 4) ^ l) & 0x0f0f0f0f; + l ^= x; + r ^= (x << 4); + + // Spread ints to bytes + x = [r, l]; + for (i = 0; i < 8; i++) { + b[i] = (x[i>>>2] >>> (8 * (3 - (i % 4)))) % 256; + if (b[i] < 0) { b[i] += 256; } // unsigned + } + return b; + } +} + +export class DESECBCipher { + constructor() { + this._cipher = null; + } + + get algorithm() { + return { name: "DES-ECB" }; + } + + static importKey(key, _algorithm, _extractable, _keyUsages) { + const cipher = new DESECBCipher; + cipher._importKey(key); + return cipher; + } + + _importKey(key, _extractable, _keyUsages) { + this._cipher = new DES(key); + } + + encrypt(_algorithm, plaintext) { + const x = new Uint8Array(plaintext); + if (x.length % 8 !== 0 || this._cipher === null) { + return null; + } + const n = x.length / 8; + for (let i = 0; i < n; i++) { + x.set(this._cipher.enc8(x.slice(i * 8, i * 8 + 8)), i * 8); + } + return x; + } +} + +export class DESCBCCipher { + constructor() { + this._cipher = null; + } + + get algorithm() { + return { name: "DES-CBC" }; + } + + static importKey(key, _algorithm, _extractable, _keyUsages) { + const cipher = new DESCBCCipher; + cipher._importKey(key); + return cipher; + } + + _importKey(key) { + this._cipher = new DES(key); + } + + encrypt(algorithm, plaintext) { + const x = new Uint8Array(plaintext); + let y = new Uint8Array(algorithm.iv); + if (x.length % 8 !== 0 || this._cipher === null) { + return null; + } + const n = x.length / 8; + for (let i = 0; i < n; i++) { + for (let j = 0; j < 8; j++) { + y[j] ^= plaintext[i * 8 + j]; + } + y = this._cipher.enc8(y); + x.set(y, i * 8); + } + return x; + } +} diff --git a/engine/static/vendor/novnc/core/crypto/dh.js b/engine/static/vendor/novnc/core/crypto/dh.js new file mode 100644 index 00000000..bd705d9b --- /dev/null +++ b/engine/static/vendor/novnc/core/crypto/dh.js @@ -0,0 +1,55 @@ +import { modPow, bigIntToU8Array, u8ArrayToBigInt } from "./bigint.js"; + +class DHPublicKey { + constructor(key) { + this._key = key; + } + + get algorithm() { + return { name: "DH" }; + } + + exportKey() { + return this._key; + } +} + +export class DHCipher { + constructor() { + this._g = null; + this._p = null; + this._gBigInt = null; + this._pBigInt = null; + this._privateKey = null; + } + + get algorithm() { + return { name: "DH" }; + } + + static generateKey(algorithm, _extractable) { + const cipher = new DHCipher; + cipher._generateKey(algorithm); + return { privateKey: cipher, publicKey: new DHPublicKey(cipher._publicKey) }; + } + + _generateKey(algorithm) { + const g = algorithm.g; + const p = algorithm.p; + this._keyBytes = p.length; + this._gBigInt = u8ArrayToBigInt(g); + this._pBigInt = u8ArrayToBigInt(p); + this._privateKey = window.crypto.getRandomValues(new Uint8Array(this._keyBytes)); + this._privateKeyBigInt = u8ArrayToBigInt(this._privateKey); + this._publicKey = bigIntToU8Array(modPow( + this._gBigInt, this._privateKeyBigInt, this._pBigInt), this._keyBytes); + } + + deriveBits(algorithm, length) { + const bytes = Math.ceil(length / 8); + const pkey = new Uint8Array(algorithm.public); + const len = bytes > this._keyBytes ? bytes : this._keyBytes; + const secret = modPow(u8ArrayToBigInt(pkey), this._privateKeyBigInt, this._pBigInt); + return bigIntToU8Array(secret, len).slice(0, len); + } +} diff --git a/engine/static/vendor/novnc/core/crypto/md5.js b/engine/static/vendor/novnc/core/crypto/md5.js new file mode 100644 index 00000000..b01ba6fd --- /dev/null +++ b/engine/static/vendor/novnc/core/crypto/md5.js @@ -0,0 +1,82 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2021 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * Performs MD5 hashing on an array of bytes, returns an array of bytes + */ + +export async function MD5(d) { + let s = ""; + for (let i = 0; i < d.length; i++) { + s += String.fromCharCode(d[i]); + } + return M(V(Y(X(s), 8 * s.length))); +} + +function M(d) { + let f = new Uint8Array(d.length); + for (let i=0;i> 2); + for (let m = 0; m < r.length; m++) r[m] = 0; + for (let m = 0; m < 8 * d.length; m += 8) r[m >> 5] |= (255 & d.charCodeAt(m / 8)) << m % 32; + return r; +} + +function V(d) { + let r = ""; + for (let m = 0; m < 32 * d.length; m += 8) r += String.fromCharCode(d[m >> 5] >>> m % 32 & 255); + return r; +} + +function Y(d, g) { + d[g >> 5] |= 128 << g % 32, d[14 + (g + 64 >>> 9 << 4)] = g; + let m = 1732584193, f = -271733879, r = -1732584194, i = 271733878; + for (let n = 0; n < d.length; n += 16) { + let h = m, + t = f, + g = r, + e = i; + f = ii(f = ii(f = ii(f = ii(f = hh(f = hh(f = hh(f = hh(f = gg(f = gg(f = gg(f = gg(f = ff(f = ff(f = ff(f = ff(f, r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 0], 7, -680876936), f, r, d[n + 1], 12, -389564586), m, f, d[n + 2], 17, 606105819), i, m, d[n + 3], 22, -1044525330), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 4], 7, -176418897), f, r, d[n + 5], 12, 1200080426), m, f, d[n + 6], 17, -1473231341), i, m, d[n + 7], 22, -45705983), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 8], 7, 1770035416), f, r, d[n + 9], 12, -1958414417), m, f, d[n + 10], 17, -42063), i, m, d[n + 11], 22, -1990404162), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 12], 7, 1804603682), f, r, d[n + 13], 12, -40341101), m, f, d[n + 14], 17, -1502002290), i, m, d[n + 15], 22, 1236535329), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 1], 5, -165796510), f, r, d[n + 6], 9, -1069501632), m, f, d[n + 11], 14, 643717713), i, m, d[n + 0], 20, -373897302), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 5], 5, -701558691), f, r, d[n + 10], 9, 38016083), m, f, d[n + 15], 14, -660478335), i, m, d[n + 4], 20, -405537848), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 9], 5, 568446438), f, r, d[n + 14], 9, -1019803690), m, f, d[n + 3], 14, -187363961), i, m, d[n + 8], 20, 1163531501), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 13], 5, -1444681467), f, r, d[n + 2], 9, -51403784), m, f, d[n + 7], 14, 1735328473), i, m, d[n + 12], 20, -1926607734), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 5], 4, -378558), f, r, d[n + 8], 11, -2022574463), m, f, d[n + 11], 16, 1839030562), i, m, d[n + 14], 23, -35309556), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 1], 4, -1530992060), f, r, d[n + 4], 11, 1272893353), m, f, d[n + 7], 16, -155497632), i, m, d[n + 10], 23, -1094730640), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 13], 4, 681279174), f, r, d[n + 0], 11, -358537222), m, f, d[n + 3], 16, -722521979), i, m, d[n + 6], 23, 76029189), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 9], 4, -640364487), f, r, d[n + 12], 11, -421815835), m, f, d[n + 15], 16, 530742520), i, m, d[n + 2], 23, -995338651), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 0], 6, -198630844), f, r, d[n + 7], 10, 1126891415), m, f, d[n + 14], 15, -1416354905), i, m, d[n + 5], 21, -57434055), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 12], 6, 1700485571), f, r, d[n + 3], 10, -1894986606), m, f, d[n + 10], 15, -1051523), i, m, d[n + 1], 21, -2054922799), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 8], 6, 1873313359), f, r, d[n + 15], 10, -30611744), m, f, d[n + 6], 15, -1560198380), i, m, d[n + 13], 21, 1309151649), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 4], 6, -145523070), f, r, d[n + 11], 10, -1120210379), m, f, d[n + 2], 15, 718787259), i, m, d[n + 9], 21, -343485551), m = add(m, h), f = add(f, t), r = add(r, g), i = add(i, e); + } + return Array(m, f, r, i); +} + +function cmn(d, g, m, f, r, i) { + return add(rol(add(add(g, d), add(f, i)), r), m); +} + +function ff(d, g, m, f, r, i, n) { + return cmn(g & m | ~g & f, d, g, r, i, n); +} + +function gg(d, g, m, f, r, i, n) { + return cmn(g & f | m & ~f, d, g, r, i, n); +} + +function hh(d, g, m, f, r, i, n) { + return cmn(g ^ m ^ f, d, g, r, i, n); +} + +function ii(d, g, m, f, r, i, n) { + return cmn(m ^ (g | ~f), d, g, r, i, n); +} + +function add(d, g) { + let m = (65535 & d) + (65535 & g); + return (d >> 16) + (g >> 16) + (m >> 16) << 16 | 65535 & m; +} + +function rol(d, g) { + return d << g | d >>> 32 - g; +} diff --git a/engine/static/vendor/novnc/core/crypto/rsa.js b/engine/static/vendor/novnc/core/crypto/rsa.js new file mode 100644 index 00000000..68e8e869 --- /dev/null +++ b/engine/static/vendor/novnc/core/crypto/rsa.js @@ -0,0 +1,132 @@ +import Base64 from "../base64.js"; +import { modPow, bigIntToU8Array, u8ArrayToBigInt } from "./bigint.js"; + +export class RSACipher { + constructor() { + this._keyLength = 0; + this._keyBytes = 0; + this._n = null; + this._e = null; + this._d = null; + this._nBigInt = null; + this._eBigInt = null; + this._dBigInt = null; + this._extractable = false; + } + + get algorithm() { + return { name: "RSA-PKCS1-v1_5" }; + } + + _base64urlDecode(data) { + data = data.replace(/-/g, "+").replace(/_/g, "/"); + data = data.padEnd(Math.ceil(data.length / 4) * 4, "="); + return Base64.decode(data); + } + + _padArray(arr, length) { + const res = new Uint8Array(length); + res.set(arr, length - arr.length); + return res; + } + + static async generateKey(algorithm, extractable, _keyUsages) { + const cipher = new RSACipher; + await cipher._generateKey(algorithm, extractable); + return { privateKey: cipher }; + } + + async _generateKey(algorithm, extractable) { + this._keyLength = algorithm.modulusLength; + this._keyBytes = Math.ceil(this._keyLength / 8); + const key = await window.crypto.subtle.generateKey( + { + name: "RSA-OAEP", + modulusLength: algorithm.modulusLength, + publicExponent: algorithm.publicExponent, + hash: {name: "SHA-256"}, + }, + true, ["encrypt", "decrypt"]); + const privateKey = await window.crypto.subtle.exportKey("jwk", key.privateKey); + this._n = this._padArray(this._base64urlDecode(privateKey.n), this._keyBytes); + this._nBigInt = u8ArrayToBigInt(this._n); + this._e = this._padArray(this._base64urlDecode(privateKey.e), this._keyBytes); + this._eBigInt = u8ArrayToBigInt(this._e); + this._d = this._padArray(this._base64urlDecode(privateKey.d), this._keyBytes); + this._dBigInt = u8ArrayToBigInt(this._d); + this._extractable = extractable; + } + + static async importKey(key, _algorithm, extractable, keyUsages) { + if (keyUsages.length !== 1 || keyUsages[0] !== "encrypt") { + throw new Error("only support importing RSA public key"); + } + const cipher = new RSACipher; + await cipher._importKey(key, extractable); + return cipher; + } + + async _importKey(key, extractable) { + const n = key.n; + const e = key.e; + if (n.length !== e.length) { + throw new Error("the sizes of modulus and public exponent do not match"); + } + this._keyBytes = n.length; + this._keyLength = this._keyBytes * 8; + this._n = new Uint8Array(this._keyBytes); + this._e = new Uint8Array(this._keyBytes); + this._n.set(n); + this._e.set(e); + this._nBigInt = u8ArrayToBigInt(this._n); + this._eBigInt = u8ArrayToBigInt(this._e); + this._extractable = extractable; + } + + async encrypt(_algorithm, message) { + if (message.length > this._keyBytes - 11) { + return null; + } + const ps = new Uint8Array(this._keyBytes - message.length - 3); + window.crypto.getRandomValues(ps); + for (let i = 0; i < ps.length; i++) { + ps[i] = Math.floor(ps[i] * 254 / 255 + 1); + } + const em = new Uint8Array(this._keyBytes); + em[1] = 0x02; + em.set(ps, 2); + em.set(message, ps.length + 3); + const emBigInt = u8ArrayToBigInt(em); + const c = modPow(emBigInt, this._eBigInt, this._nBigInt); + return bigIntToU8Array(c, this._keyBytes); + } + + async decrypt(_algorithm, message) { + if (message.length !== this._keyBytes) { + return null; + } + const msgBigInt = u8ArrayToBigInt(message); + const emBigInt = modPow(msgBigInt, this._dBigInt, this._nBigInt); + const em = bigIntToU8Array(emBigInt, this._keyBytes); + if (em[0] !== 0x00 || em[1] !== 0x02) { + return null; + } + let i = 2; + for (; i < em.length; i++) { + if (em[i] === 0x00) { + break; + } + } + if (i === em.length) { + return null; + } + return em.slice(i + 1, em.length); + } + + async exportKey() { + if (!this._extractable) { + throw new Error("key is not extractable"); + } + return { n: this._n, e: this._e, d: this._d }; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/copyrect.js b/engine/static/vendor/novnc/core/decoders/copyrect.js new file mode 100644 index 00000000..3c7e0d5d --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/copyrect.js @@ -0,0 +1,27 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class CopyRectDecoder { + decodeRect(x, y, width, height, sock, display, depth) { + if (sock.rQwait("COPYRECT", 4)) { + return false; + } + + let deltaX = sock.rQshift16(); + let deltaY = sock.rQshift16(); + + if ((width === 0) || (height === 0)) { + return true; + } + + display.copyImage(deltaX, deltaY, x, y, width, height); + + return true; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/h264.js b/engine/static/vendor/novnc/core/decoders/h264.js new file mode 100644 index 00000000..a508b674 --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/h264.js @@ -0,0 +1,321 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2024 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import * as Log from '../util/logging.js'; + +export class H264Parser { + constructor(data) { + this._data = data; + this._index = 0; + this.profileIdc = null; + this.constraintSet = null; + this.levelIdc = null; + } + + _getStartSequenceLen(index) { + let data = this._data; + if (data[index + 0] == 0 && data[index + 1] == 0 && data[index + 2] == 0 && data[index + 3] == 1) { + return 4; + } + if (data[index + 0] == 0 && data[index + 1] == 0 && data[index + 2] == 1) { + return 3; + } + return 0; + } + + _indexOfNextNalUnit(index) { + let data = this._data; + for (let i = index; i < data.length; ++i) { + if (this._getStartSequenceLen(i) != 0) { + return i; + } + } + return -1; + } + + _parseSps(index) { + this.profileIdc = this._data[index]; + this.constraintSet = this._data[index + 1]; + this.levelIdc = this._data[index + 2]; + } + + _parseNalUnit(index) { + const firstByte = this._data[index]; + if (firstByte & 0x80) { + throw new Error('H264 parsing sanity check failed, forbidden zero bit is set'); + } + const unitType = firstByte & 0x1f; + + switch (unitType) { + case 1: // coded slice, non-idr + return { slice: true }; + case 5: // coded slice, idr + return { slice: true, key: true }; + case 6: // sei + return {}; + case 7: // sps + this._parseSps(index + 1); + return {}; + case 8: // pps + return {}; + default: + Log.Warn("Unhandled unit type: ", unitType); + break; + } + return {}; + } + + parse() { + const startIndex = this._index; + let isKey = false; + + while (this._index < this._data.length) { + const startSequenceLen = this._getStartSequenceLen(this._index); + if (startSequenceLen == 0) { + throw new Error('Invalid start sequence in bit stream'); + } + + const { slice, key } = this._parseNalUnit(this._index + startSequenceLen); + + let nextIndex = this._indexOfNextNalUnit(this._index + startSequenceLen); + if (nextIndex == -1) { + this._index = this._data.length; + } else { + this._index = nextIndex; + } + + if (key) { + isKey = true; + } + if (slice) { + break; + } + } + + if (startIndex === this._index) { + return null; + } + + return { + frame: this._data.subarray(startIndex, this._index), + key: isKey, + }; + } +} + +export class H264Context { + constructor(width, height) { + this.lastUsed = 0; + this._width = width; + this._height = height; + this._profileIdc = null; + this._constraintSet = null; + this._levelIdc = null; + this._decoder = null; + this._pendingFrames = []; + } + + _handleFrame(frame) { + let pending = this._pendingFrames.shift(); + if (pending === undefined) { + throw new Error("Pending frame queue empty when receiving frame from decoder"); + } + + if (pending.timestamp != frame.timestamp) { + throw new Error("Video frame timestamp mismatch. Expected " + + frame.timestamp + " but but got " + pending.timestamp); + } + + pending.frame = frame; + pending.ready = true; + pending.resolve(); + + if (!pending.keep) { + frame.close(); + } + } + + _handleError(e) { + throw new Error("Failed to decode frame: " + e.message); + } + + _configureDecoder(profileIdc, constraintSet, levelIdc) { + if (this._decoder === null || this._decoder.state === 'closed') { + this._decoder = new VideoDecoder({ + output: frame => this._handleFrame(frame), + error: e => this._handleError(e), + }); + } + const codec = 'avc1.' + + profileIdc.toString(16).padStart(2, '0') + + constraintSet.toString(16).padStart(2, '0') + + levelIdc.toString(16).padStart(2, '0'); + this._decoder.configure({ + codec: codec, + codedWidth: this._width, + codedHeight: this._height, + optimizeForLatency: true, + }); + } + + _preparePendingFrame(timestamp) { + let pending = { + timestamp: timestamp, + promise: null, + resolve: null, + frame: null, + ready: false, + keep: false, + }; + pending.promise = new Promise((resolve) => { + pending.resolve = resolve; + }); + this._pendingFrames.push(pending); + + return pending; + } + + decode(payload) { + let parser = new H264Parser(payload); + let result = null; + + // Ideally, this timestamp should come from the server, but we'll just + // approximate it instead. + let timestamp = Math.round(window.performance.now() * 1e3); + + while (true) { + let encodedFrame = parser.parse(); + if (encodedFrame === null) { + break; + } + + if (parser.profileIdc !== null) { + self._profileIdc = parser.profileIdc; + self._constraintSet = parser.constraintSet; + self._levelIdc = parser.levelIdc; + } + + if (this._decoder === null || this._decoder.state !== 'configured') { + if (!encodedFrame.key) { + Log.Warn("Missing key frame. Can't decode until one arrives"); + continue; + } + if (self._profileIdc === null) { + Log.Warn('Cannot config decoder. Have not received SPS and PPS yet.'); + continue; + } + this._configureDecoder(self._profileIdc, self._constraintSet, + self._levelIdc); + } + + result = this._preparePendingFrame(timestamp); + + const chunk = new EncodedVideoChunk({ + timestamp: timestamp, + type: encodedFrame.key ? 'key' : 'delta', + data: encodedFrame.frame, + }); + + try { + this._decoder.decode(chunk); + } catch (e) { + Log.Warn("Failed to decode:", e); + } + } + + // We only keep last frame of each payload + if (result !== null) { + result.keep = true; + } + + return result; + } +} + +export default class H264Decoder { + constructor() { + this._tick = 0; + this._contexts = {}; + } + + _contextId(x, y, width, height) { + return [x, y, width, height].join(','); + } + + _findOldestContextId() { + let oldestTick = Number.MAX_VALUE; + let oldestKey = undefined; + for (const [key, value] of Object.entries(this._contexts)) { + if (value.lastUsed < oldestTick) { + oldestTick = value.lastUsed; + oldestKey = key; + } + } + return oldestKey; + } + + _createContext(x, y, width, height) { + const maxContexts = 64; + if (Object.keys(this._contexts).length >= maxContexts) { + let oldestContextId = this._findOldestContextId(); + delete this._contexts[oldestContextId]; + } + let context = new H264Context(width, height); + this._contexts[this._contextId(x, y, width, height)] = context; + return context; + } + + _getContext(x, y, width, height) { + let context = this._contexts[this._contextId(x, y, width, height)]; + return context !== undefined ? context : this._createContext(x, y, width, height); + } + + _resetContext(x, y, width, height) { + delete this._contexts[this._contextId(x, y, width, height)]; + } + + _resetAllContexts() { + this._contexts = {}; + } + + decodeRect(x, y, width, height, sock, display, depth) { + const resetContextFlag = 1; + const resetAllContextsFlag = 2; + + if (sock.rQwait("h264 header", 8)) { + return false; + } + + const length = sock.rQshift32(); + const flags = sock.rQshift32(); + + if (sock.rQwait("h264 payload", length, 8)) { + return false; + } + + if (flags & resetAllContextsFlag) { + this._resetAllContexts(); + } else if (flags & resetContextFlag) { + this._resetContext(x, y, width, height); + } + + let context = this._getContext(x, y, width, height); + context.lastUsed = this._tick++; + + if (length !== 0) { + let payload = sock.rQshiftBytes(length, false); + let frame = context.decode(payload); + if (frame !== null) { + display.videoFrame(x, y, width, height, frame); + } + } + + return true; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/hextile.js b/engine/static/vendor/novnc/core/decoders/hextile.js new file mode 100644 index 00000000..db0792bd --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/hextile.js @@ -0,0 +1,181 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import * as Log from '../util/logging.js'; + +export default class HextileDecoder { + constructor() { + this._tiles = 0; + this._lastsubencoding = 0; + this._tileBuffer = new Uint8Array(16 * 16 * 4); + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._tiles === 0) { + this._tilesX = Math.ceil(width / 16); + this._tilesY = Math.ceil(height / 16); + this._totalTiles = this._tilesX * this._tilesY; + this._tiles = this._totalTiles; + } + + while (this._tiles > 0) { + let bytes = 1; + + if (sock.rQwait("HEXTILE", bytes)) { + return false; + } + + let subencoding = sock.rQpeek8(); + if (subencoding > 30) { // Raw + throw new Error("Illegal hextile subencoding (subencoding: " + + subencoding + ")"); + } + + const currTile = this._totalTiles - this._tiles; + const tileX = currTile % this._tilesX; + const tileY = Math.floor(currTile / this._tilesX); + const tx = x + tileX * 16; + const ty = y + tileY * 16; + const tw = Math.min(16, (x + width) - tx); + const th = Math.min(16, (y + height) - ty); + + // Figure out how much we are expecting + if (subencoding & 0x01) { // Raw + bytes += tw * th * 4; + } else { + if (subencoding & 0x02) { // Background + bytes += 4; + } + if (subencoding & 0x04) { // Foreground + bytes += 4; + } + if (subencoding & 0x08) { // AnySubrects + bytes++; // Since we aren't shifting it off + + if (sock.rQwait("HEXTILE", bytes)) { + return false; + } + + let subrects = sock.rQpeekBytes(bytes).at(-1); + if (subencoding & 0x10) { // SubrectsColoured + bytes += subrects * (4 + 2); + } else { + bytes += subrects * 2; + } + } + } + + if (sock.rQwait("HEXTILE", bytes)) { + return false; + } + + // We know the encoding and have a whole tile + sock.rQshift8(); + if (subencoding === 0) { + if (this._lastsubencoding & 0x01) { + // Weird: ignore blanks are RAW + Log.Debug(" Ignoring blank after RAW"); + } else { + display.fillRect(tx, ty, tw, th, this._background); + } + } else if (subencoding & 0x01) { // Raw + let pixels = tw * th; + let data = sock.rQshiftBytes(pixels * 4, false); + // Max sure the image is fully opaque + for (let i = 0;i < pixels;i++) { + data[i * 4 + 3] = 255; + } + display.blitImage(tx, ty, tw, th, data, 0); + } else { + if (subencoding & 0x02) { // Background + this._background = new Uint8Array(sock.rQshiftBytes(4)); + } + if (subencoding & 0x04) { // Foreground + this._foreground = new Uint8Array(sock.rQshiftBytes(4)); + } + + this._startTile(tx, ty, tw, th, this._background); + if (subencoding & 0x08) { // AnySubrects + let subrects = sock.rQshift8(); + + for (let s = 0; s < subrects; s++) { + let color; + if (subencoding & 0x10) { // SubrectsColoured + color = sock.rQshiftBytes(4); + } else { + color = this._foreground; + } + const xy = sock.rQshift8(); + const sx = (xy >> 4); + const sy = (xy & 0x0f); + + const wh = sock.rQshift8(); + const sw = (wh >> 4) + 1; + const sh = (wh & 0x0f) + 1; + + this._subTile(sx, sy, sw, sh, color); + } + } + this._finishTile(display); + } + this._lastsubencoding = subencoding; + this._tiles--; + } + + return true; + } + + // start updating a tile + _startTile(x, y, width, height, color) { + this._tileX = x; + this._tileY = y; + this._tileW = width; + this._tileH = height; + + const red = color[0]; + const green = color[1]; + const blue = color[2]; + + const data = this._tileBuffer; + for (let i = 0; i < width * height * 4; i += 4) { + data[i] = red; + data[i + 1] = green; + data[i + 2] = blue; + data[i + 3] = 255; + } + } + + // update sub-rectangle of the current tile + _subTile(x, y, w, h, color) { + const red = color[0]; + const green = color[1]; + const blue = color[2]; + const xend = x + w; + const yend = y + h; + + const data = this._tileBuffer; + const width = this._tileW; + for (let j = y; j < yend; j++) { + for (let i = x; i < xend; i++) { + const p = (i + (j * width)) * 4; + data[p] = red; + data[p + 1] = green; + data[p + 2] = blue; + data[p + 3] = 255; + } + } + } + + // draw the current tile to the screen + _finishTile(display) { + display.blitImage(this._tileX, this._tileY, + this._tileW, this._tileH, + this._tileBuffer, 0); + } +} diff --git a/engine/static/vendor/novnc/core/decoders/jpeg.js b/engine/static/vendor/novnc/core/decoders/jpeg.js new file mode 100644 index 00000000..f7984603 --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/jpeg.js @@ -0,0 +1,161 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class JPEGDecoder { + constructor() { + // RealVNC will reuse the quantization tables + // and Huffman tables, so we need to cache them. + this._cachedQuantTables = []; + this._cachedHuffmanTables = []; + + this._segments = []; + } + + decodeRect(x, y, width, height, sock, display, depth) { + // A rect of JPEG encodings is simply a JPEG file + while (true) { + let segment = this._readSegment(sock); + if (segment === null) { + return false; + } + this._segments.push(segment); + // End of image? + if (segment[1] === 0xD9) { + break; + } + } + + let huffmanTables = []; + let quantTables = []; + for (let segment of this._segments) { + let type = segment[1]; + if (type === 0xC4) { + // Huffman tables + huffmanTables.push(segment); + } else if (type === 0xDB) { + // Quantization tables + quantTables.push(segment); + } + } + + const sofIndex = this._segments.findIndex( + x => x[1] == 0xC0 || x[1] == 0xC2 + ); + if (sofIndex == -1) { + throw new Error("Illegal JPEG image without SOF"); + } + + if (quantTables.length === 0) { + this._segments.splice(sofIndex+1, 0, + ...this._cachedQuantTables); + } + if (huffmanTables.length === 0) { + this._segments.splice(sofIndex+1, 0, + ...this._cachedHuffmanTables); + } + + let length = 0; + for (let segment of this._segments) { + length += segment.length; + } + + let data = new Uint8Array(length); + length = 0; + for (let segment of this._segments) { + data.set(segment, length); + length += segment.length; + } + + display.imageRect(x, y, width, height, "image/jpeg", data); + + if (huffmanTables.length !== 0) { + this._cachedHuffmanTables = huffmanTables; + } + if (quantTables.length !== 0) { + this._cachedQuantTables = quantTables; + } + + this._segments = []; + + return true; + } + + _readSegment(sock) { + if (sock.rQwait("JPEG", 2)) { + return null; + } + + let marker = sock.rQshift8(); + if (marker != 0xFF) { + throw new Error("Illegal JPEG marker received (byte: " + + marker + ")"); + } + let type = sock.rQshift8(); + if (type >= 0xD0 && type <= 0xD9 || type == 0x01) { + // No length after marker + return new Uint8Array([marker, type]); + } + + if (sock.rQwait("JPEG", 2, 2)) { + return null; + } + + let length = sock.rQshift16(); + if (length < 2) { + throw new Error("Illegal JPEG length received (length: " + + length + ")"); + } + + if (sock.rQwait("JPEG", length-2, 4)) { + return null; + } + + let extra = 0; + if (type === 0xDA) { + // start of scan + if (sock.rQwait("JPEG", length-2 + 2, 4)) { + return null; + } + + let len = sock.rQlen(); + let data = sock.rQpeekBytes(len, false); + + while (true) { + let idx = data.indexOf(0xFF, length-2+extra); + if (idx === -1) { + sock.rQwait("JPEG", Infinity, 4); + return null; + } + + if (idx === len-1) { + sock.rQwait("JPEG", Infinity, 4); + return null; + } + + if (data.at(idx+1) === 0x00 || + (data.at(idx+1) >= 0xD0 && data.at(idx+1) <= 0xD7)) { + extra = idx+2 - (length-2); + continue; + } + + extra = idx - (length-2); + break; + } + } + + let segment = new Uint8Array(2 + length + extra); + segment[0] = marker; + segment[1] = type; + segment[2] = length >> 8; + segment[3] = length; + segment.set(sock.rQshiftBytes(length-2+extra, false), 4); + + return segment; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/raw.js b/engine/static/vendor/novnc/core/decoders/raw.js new file mode 100644 index 00000000..bd5d2044 --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/raw.js @@ -0,0 +1,59 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class RawDecoder { + constructor() { + this._lines = 0; + } + + decodeRect(x, y, width, height, sock, display, depth) { + if ((width === 0) || (height === 0)) { + return true; + } + + if (this._lines === 0) { + this._lines = height; + } + + const pixelSize = depth == 8 ? 1 : 4; + const bytesPerLine = width * pixelSize; + + while (this._lines > 0) { + if (sock.rQwait("RAW", bytesPerLine)) { + return false; + } + + const curY = y + (height - this._lines); + + let data = sock.rQshiftBytes(bytesPerLine, false); + + // Convert data if needed + if (depth == 8) { + const newdata = new Uint8Array(width * 4); + for (let i = 0; i < width; i++) { + newdata[i * 4 + 0] = ((data[i] >> 0) & 0x3) * 255 / 3; + newdata[i * 4 + 1] = ((data[i] >> 2) & 0x3) * 255 / 3; + newdata[i * 4 + 2] = ((data[i] >> 4) & 0x3) * 255 / 3; + newdata[i * 4 + 3] = 255; + } + data = newdata; + } + + // Max sure the image is fully opaque + for (let i = 0; i < width; i++) { + data[i * 4 + 3] = 255; + } + + display.blitImage(x, curY, width, 1, data, 0); + this._lines--; + } + + return true; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/rre.js b/engine/static/vendor/novnc/core/decoders/rre.js new file mode 100644 index 00000000..a5fea7c4 --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/rre.js @@ -0,0 +1,44 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class RREDecoder { + constructor() { + this._subrects = 0; + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._subrects === 0) { + if (sock.rQwait("RRE", 4 + 4)) { + return false; + } + + this._subrects = sock.rQshift32(); + + let color = sock.rQshiftBytes(4); // Background + display.fillRect(x, y, width, height, color); + } + + while (this._subrects > 0) { + if (sock.rQwait("RRE", 4 + 8)) { + return false; + } + + let color = sock.rQshiftBytes(4); + let sx = sock.rQshift16(); + let sy = sock.rQshift16(); + let swidth = sock.rQshift16(); + let sheight = sock.rQshift16(); + display.fillRect(x + sx, y + sy, swidth, sheight, color); + + this._subrects--; + } + + return true; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/tight.js b/engine/static/vendor/novnc/core/decoders/tight.js new file mode 100644 index 00000000..1a145d4e --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/tight.js @@ -0,0 +1,393 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca) + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import * as Log from '../util/logging.js'; +import Inflator from "../inflator.js"; + +export default class TightDecoder { + constructor() { + this._ctl = null; + this._filter = null; + this._numColors = 0; + this._palette = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel) + this._len = 0; + + this._zlibs = []; + for (let i = 0; i < 4; i++) { + this._zlibs[i] = new Inflator(); + } + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._ctl === null) { + if (sock.rQwait("TIGHT compression-control", 1)) { + return false; + } + + this._ctl = sock.rQshift8(); + + // Reset streams if the server requests it + for (let i = 0; i < 4; i++) { + if ((this._ctl >> i) & 1) { + this._zlibs[i].reset(); + Log.Info("Reset zlib stream " + i); + } + } + + // Figure out filter + this._ctl = this._ctl >> 4; + } + + let ret; + + if (this._ctl === 0x08) { + ret = this._fillRect(x, y, width, height, + sock, display, depth); + } else if (this._ctl === 0x09) { + ret = this._jpegRect(x, y, width, height, + sock, display, depth); + } else if (this._ctl === 0x0A) { + ret = this._pngRect(x, y, width, height, + sock, display, depth); + } else if ((this._ctl & 0x08) == 0) { + ret = this._basicRect(this._ctl, x, y, width, height, + sock, display, depth); + } else { + throw new Error("Illegal tight compression received (ctl: " + + this._ctl + ")"); + } + + if (ret) { + this._ctl = null; + } + + return ret; + } + + _fillRect(x, y, width, height, sock, display, depth) { + if (sock.rQwait("TIGHT", 3)) { + return false; + } + + let pixel = sock.rQshiftBytes(3); + display.fillRect(x, y, width, height, pixel, false); + + return true; + } + + _jpegRect(x, y, width, height, sock, display, depth) { + let data = this._readData(sock); + if (data === null) { + return false; + } + + display.imageRect(x, y, width, height, "image/jpeg", data); + + return true; + } + + _pngRect(x, y, width, height, sock, display, depth) { + throw new Error("PNG received in standard Tight rect"); + } + + _basicRect(ctl, x, y, width, height, sock, display, depth) { + if (this._filter === null) { + if (ctl & 0x4) { + if (sock.rQwait("TIGHT", 1)) { + return false; + } + + this._filter = sock.rQshift8(); + } else { + // Implicit CopyFilter + this._filter = 0; + } + } + + let streamId = ctl & 0x3; + + let ret; + + switch (this._filter) { + case 0: // CopyFilter + ret = this._copyFilter(streamId, x, y, width, height, + sock, display, depth); + break; + case 1: // PaletteFilter + ret = this._paletteFilter(streamId, x, y, width, height, + sock, display, depth); + break; + case 2: // GradientFilter + ret = this._gradientFilter(streamId, x, y, width, height, + sock, display, depth); + break; + default: + throw new Error("Illegal tight filter received (ctl: " + + this._filter + ")"); + } + + if (ret) { + this._filter = null; + } + + return ret; + } + + _copyFilter(streamId, x, y, width, height, sock, display, depth) { + const uncompressedSize = width * height * 3; + let data; + + if (uncompressedSize === 0) { + return true; + } + + if (uncompressedSize < 12) { + if (sock.rQwait("TIGHT", uncompressedSize)) { + return false; + } + + data = sock.rQshiftBytes(uncompressedSize); + } else { + data = this._readData(sock); + if (data === null) { + return false; + } + + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); + } + + let rgbx = new Uint8Array(width * height * 4); + for (let i = 0, j = 0; i < width * height * 4; i += 4, j += 3) { + rgbx[i] = data[j]; + rgbx[i + 1] = data[j + 1]; + rgbx[i + 2] = data[j + 2]; + rgbx[i + 3] = 255; // Alpha + } + + display.blitImage(x, y, width, height, rgbx, 0, false); + + return true; + } + + _paletteFilter(streamId, x, y, width, height, sock, display, depth) { + if (this._numColors === 0) { + if (sock.rQwait("TIGHT palette", 1)) { + return false; + } + + const numColors = sock.rQpeek8() + 1; + const paletteSize = numColors * 3; + + if (sock.rQwait("TIGHT palette", 1 + paletteSize)) { + return false; + } + + this._numColors = numColors; + sock.rQskipBytes(1); + + sock.rQshiftTo(this._palette, paletteSize); + } + + const bpp = (this._numColors <= 2) ? 1 : 8; + const rowSize = Math.floor((width * bpp + 7) / 8); + const uncompressedSize = rowSize * height; + + let data; + + if (uncompressedSize === 0) { + return true; + } + + if (uncompressedSize < 12) { + if (sock.rQwait("TIGHT", uncompressedSize)) { + return false; + } + + data = sock.rQshiftBytes(uncompressedSize); + } else { + data = this._readData(sock); + if (data === null) { + return false; + } + + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); + } + + // Convert indexed (palette based) image data to RGB + if (this._numColors == 2) { + this._monoRect(x, y, width, height, data, this._palette, display); + } else { + this._paletteRect(x, y, width, height, data, this._palette, display); + } + + this._numColors = 0; + + return true; + } + + _monoRect(x, y, width, height, data, palette, display) { + // Convert indexed (palette based) image data to RGB + // TODO: reduce number of calculations inside loop + const dest = this._getScratchBuffer(width * height * 4); + const w = Math.floor((width + 7) / 8); + const w1 = Math.floor(width / 8); + + for (let y = 0; y < height; y++) { + let dp, sp, x; + for (x = 0; x < w1; x++) { + for (let b = 7; b >= 0; b--) { + dp = (y * width + x * 8 + 7 - b) * 4; + sp = (data[y * w + x] >> b & 1) * 3; + dest[dp] = palette[sp]; + dest[dp + 1] = palette[sp + 1]; + dest[dp + 2] = palette[sp + 2]; + dest[dp + 3] = 255; + } + } + + for (let b = 7; b >= 8 - width % 8; b--) { + dp = (y * width + x * 8 + 7 - b) * 4; + sp = (data[y * w + x] >> b & 1) * 3; + dest[dp] = palette[sp]; + dest[dp + 1] = palette[sp + 1]; + dest[dp + 2] = palette[sp + 2]; + dest[dp + 3] = 255; + } + } + + display.blitImage(x, y, width, height, dest, 0, false); + } + + _paletteRect(x, y, width, height, data, palette, display) { + // Convert indexed (palette based) image data to RGB + const dest = this._getScratchBuffer(width * height * 4); + const total = width * height * 4; + for (let i = 0, j = 0; i < total; i += 4, j++) { + const sp = data[j] * 3; + dest[i] = palette[sp]; + dest[i + 1] = palette[sp + 1]; + dest[i + 2] = palette[sp + 2]; + dest[i + 3] = 255; + } + + display.blitImage(x, y, width, height, dest, 0, false); + } + + _gradientFilter(streamId, x, y, width, height, sock, display, depth) { + // assume the TPIXEL is 3 bytes long + const uncompressedSize = width * height * 3; + let data; + + if (uncompressedSize === 0) { + return true; + } + + if (uncompressedSize < 12) { + if (sock.rQwait("TIGHT", uncompressedSize)) { + return false; + } + + data = sock.rQshiftBytes(uncompressedSize); + } else { + data = this._readData(sock); + if (data === null) { + return false; + } + + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); + } + + let rgbx = new Uint8Array(4 * width * height); + + let rgbxIndex = 0, dataIndex = 0; + let left = new Uint8Array(3); + for (let x = 0; x < width; x++) { + for (let c = 0; c < 3; c++) { + const prediction = left[c]; + const value = data[dataIndex++] + prediction; + rgbx[rgbxIndex++] = value; + left[c] = value; + } + rgbx[rgbxIndex++] = 255; + } + + let upperIndex = 0; + let upper = new Uint8Array(3), + upperleft = new Uint8Array(3); + for (let y = 1; y < height; y++) { + left.fill(0); + upperleft.fill(0); + for (let x = 0; x < width; x++) { + for (let c = 0; c < 3; c++) { + upper[c] = rgbx[upperIndex++]; + let prediction = left[c] + upper[c] - upperleft[c]; + if (prediction < 0) { + prediction = 0; + } else if (prediction > 255) { + prediction = 255; + } + const value = data[dataIndex++] + prediction; + rgbx[rgbxIndex++] = value; + upperleft[c] = upper[c]; + left[c] = value; + } + rgbx[rgbxIndex++] = 255; + upperIndex++; + } + } + + display.blitImage(x, y, width, height, rgbx, 0, false); + + return true; + } + + _readData(sock) { + if (this._len === 0) { + if (sock.rQwait("TIGHT", 3)) { + return null; + } + + let byte; + + byte = sock.rQshift8(); + this._len = byte & 0x7f; + if (byte & 0x80) { + byte = sock.rQshift8(); + this._len |= (byte & 0x7f) << 7; + if (byte & 0x80) { + byte = sock.rQshift8(); + this._len |= byte << 14; + } + } + } + + if (sock.rQwait("TIGHT", this._len)) { + return null; + } + + let data = sock.rQshiftBytes(this._len, false); + this._len = 0; + + return data; + } + + _getScratchBuffer(size) { + if (!this._scratchBuffer || (this._scratchBuffer.length < size)) { + this._scratchBuffer = new Uint8Array(size); + } + return this._scratchBuffer; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/tightpng.js b/engine/static/vendor/novnc/core/decoders/tightpng.js new file mode 100644 index 00000000..cf1df6ba --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/tightpng.js @@ -0,0 +1,27 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import TightDecoder from './tight.js'; + +export default class TightPNGDecoder extends TightDecoder { + _pngRect(x, y, width, height, sock, display, depth) { + let data = this._readData(sock); + if (data === null) { + return false; + } + + display.imageRect(x, y, width, height, "image/png", data); + + return true; + } + + _basicRect(ctl, x, y, width, height, sock, display, depth) { + throw new Error("BasicCompression received in TightPNG rect"); + } +} diff --git a/engine/static/vendor/novnc/core/decoders/zlib.js b/engine/static/vendor/novnc/core/decoders/zlib.js new file mode 100644 index 00000000..a876908b --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/zlib.js @@ -0,0 +1,51 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2024 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import Inflator from "../inflator.js"; + +export default class ZlibDecoder { + constructor() { + this._zlib = new Inflator(); + this._length = 0; + } + + decodeRect(x, y, width, height, sock, display, depth) { + if ((width === 0) || (height === 0)) { + return true; + } + + if (this._length === 0) { + if (sock.rQwait("ZLIB", 4)) { + return false; + } + + this._length = sock.rQshift32(); + } + + if (sock.rQwait("ZLIB", this._length)) { + return false; + } + + let data = new Uint8Array(sock.rQshiftBytes(this._length, false)); + this._length = 0; + + this._zlib.setInput(data); + data = this._zlib.inflate(width * height * 4); + this._zlib.setInput(null); + + // Max sure the image is fully opaque + for (let i = 0; i < width * height; i++) { + data[i * 4 + 3] = 255; + } + + display.blitImage(x, y, width, height, data, 0); + + return true; + } +} diff --git a/engine/static/vendor/novnc/core/decoders/zrle.js b/engine/static/vendor/novnc/core/decoders/zrle.js new file mode 100644 index 00000000..ef1726f6 --- /dev/null +++ b/engine/static/vendor/novnc/core/decoders/zrle.js @@ -0,0 +1,185 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2021 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import Inflate from "../inflator.js"; + +const ZRLE_TILE_WIDTH = 64; +const ZRLE_TILE_HEIGHT = 64; + +export default class ZRLEDecoder { + constructor() { + this._length = 0; + this._inflator = new Inflate(); + + this._pixelBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4); + this._tileBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4); + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._length === 0) { + if (sock.rQwait("ZLib data length", 4)) { + return false; + } + this._length = sock.rQshift32(); + } + if (sock.rQwait("Zlib data", this._length)) { + return false; + } + + const data = sock.rQshiftBytes(this._length, false); + + this._inflator.setInput(data); + + for (let ty = y; ty < y + height; ty += ZRLE_TILE_HEIGHT) { + let th = Math.min(ZRLE_TILE_HEIGHT, y + height - ty); + + for (let tx = x; tx < x + width; tx += ZRLE_TILE_WIDTH) { + let tw = Math.min(ZRLE_TILE_WIDTH, x + width - tx); + + const tileSize = tw * th; + const subencoding = this._inflator.inflate(1)[0]; + if (subencoding === 0) { + // raw data + const data = this._readPixels(tileSize); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else if (subencoding === 1) { + // solid + const background = this._readPixels(1); + display.fillRect(tx, ty, tw, th, [background[0], background[1], background[2]]); + } else if (subencoding >= 2 && subencoding <= 16) { + const data = this._decodePaletteTile(subencoding, tileSize, tw, th); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else if (subencoding === 128) { + const data = this._decodeRLETile(tileSize); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else if (subencoding >= 130 && subencoding <= 255) { + const data = this._decodeRLEPaletteTile(subencoding - 128, tileSize); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else { + throw new Error('Unknown subencoding: ' + subencoding); + } + } + } + this._length = 0; + return true; + } + + _getBitsPerPixelInPalette(paletteSize) { + if (paletteSize <= 2) { + return 1; + } else if (paletteSize <= 4) { + return 2; + } else if (paletteSize <= 16) { + return 4; + } + } + + _readPixels(pixels) { + let data = this._pixelBuffer; + const buffer = this._inflator.inflate(3*pixels); + for (let i = 0, j = 0; i < pixels*4; i += 4, j += 3) { + data[i] = buffer[j]; + data[i + 1] = buffer[j + 1]; + data[i + 2] = buffer[j + 2]; + data[i + 3] = 255; // Add the Alpha + } + return data; + } + + _decodePaletteTile(paletteSize, tileSize, tilew, tileh) { + const data = this._tileBuffer; + const palette = this._readPixels(paletteSize); + const bitsPerPixel = this._getBitsPerPixelInPalette(paletteSize); + const mask = (1 << bitsPerPixel) - 1; + + let offset = 0; + let encoded = this._inflator.inflate(1)[0]; + + for (let y=0; y>shift) & mask; + + data[offset] = palette[indexInPalette * 4]; + data[offset + 1] = palette[indexInPalette * 4 + 1]; + data[offset + 2] = palette[indexInPalette * 4 + 2]; + data[offset + 3] = palette[indexInPalette * 4 + 3]; + offset += 4; + shift-=bitsPerPixel; + } + if (shift<8-bitsPerPixel && y= 128) { + indexInPalette -= 128; + length = this._readRLELength(); + } + if (indexInPalette > paletteSize) { + throw new Error('Too big index in palette: ' + indexInPalette + ', palette size: ' + paletteSize); + } + if (offset + length > tileSize) { + throw new Error('Too big rle length in palette mode: ' + length + ', allowed length is: ' + (tileSize - offset)); + } + + for (let j = 0; j < length; j++) { + data[offset * 4] = palette[indexInPalette * 4]; + data[offset * 4 + 1] = palette[indexInPalette * 4 + 1]; + data[offset * 4 + 2] = palette[indexInPalette * 4 + 2]; + data[offset * 4 + 3] = palette[indexInPalette * 4 + 3]; + offset++; + } + } + return data; + } + + _readRLELength() { + let length = 0; + let current = 0; + do { + current = this._inflator.inflate(1)[0]; + length += current; + } while (current === 255); + return length + 1; + } +} diff --git a/engine/static/vendor/novnc/core/deflator.js b/engine/static/vendor/novnc/core/deflator.js new file mode 100644 index 00000000..af24009e --- /dev/null +++ b/engine/static/vendor/novnc/core/deflator.js @@ -0,0 +1,84 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +import { deflateInit, deflate } from "../vendor/pako/lib/zlib/deflate.js"; +import { Z_FULL_FLUSH, Z_DEFAULT_COMPRESSION } from "../vendor/pako/lib/zlib/deflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; + +export default class Deflator { + constructor() { + this.strm = new ZStream(); + this.chunkSize = 1024 * 10 * 10; + this.outputBuffer = new Uint8Array(this.chunkSize); + + deflateInit(this.strm, Z_DEFAULT_COMPRESSION); + } + + deflate(inData) { + /* eslint-disable camelcase */ + this.strm.input = inData; + this.strm.avail_in = this.strm.input.length; + this.strm.next_in = 0; + this.strm.output = this.outputBuffer; + this.strm.avail_out = this.chunkSize; + this.strm.next_out = 0; + /* eslint-enable camelcase */ + + let lastRet = deflate(this.strm, Z_FULL_FLUSH); + let outData = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + + if (lastRet < 0) { + throw new Error("zlib deflate failed"); + } + + if (this.strm.avail_in > 0) { + // Read chunks until done + + let chunks = [outData]; + let totalLen = outData.length; + do { + /* eslint-disable camelcase */ + this.strm.output = new Uint8Array(this.chunkSize); + this.strm.next_out = 0; + this.strm.avail_out = this.chunkSize; + /* eslint-enable camelcase */ + + lastRet = deflate(this.strm, Z_FULL_FLUSH); + + if (lastRet < 0) { + throw new Error("zlib deflate failed"); + } + + let chunk = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + totalLen += chunk.length; + chunks.push(chunk); + } while (this.strm.avail_in > 0); + + // Combine chunks into a single data + + let newData = new Uint8Array(totalLen); + let offset = 0; + + for (let i = 0; i < chunks.length; i++) { + newData.set(chunks[i], offset); + offset += chunks[i].length; + } + + outData = newData; + } + + /* eslint-disable camelcase */ + this.strm.input = null; + this.strm.avail_in = 0; + this.strm.next_in = 0; + /* eslint-enable camelcase */ + + return outData; + } + +} diff --git a/engine/static/vendor/novnc/core/display.js b/engine/static/vendor/novnc/core/display.js new file mode 100644 index 00000000..4efd6f4b --- /dev/null +++ b/engine/static/vendor/novnc/core/display.js @@ -0,0 +1,578 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +import * as Log from './util/logging.js'; +import Base64 from "./base64.js"; +import { toSigned32bit } from './util/int.js'; + +export default class Display { + constructor(target) { + this._drawCtx = null; + + this._renderQ = []; // queue drawing actions for in-oder rendering + this._flushPromise = null; + + // the full frame buffer (logical canvas) size + this._fbWidth = 0; + this._fbHeight = 0; + + this._prevDrawStyle = ""; + + Log.Debug(">> Display.constructor"); + + // The visible canvas + this._target = target; + + if (!this._target) { + throw new Error("Target must be set"); + } + + if (typeof this._target === 'string') { + throw new Error('target must be a DOM element'); + } + + if (!this._target.getContext) { + throw new Error("no getContext method"); + } + + this._targetCtx = this._target.getContext('2d'); + + // the visible canvas viewport (i.e. what actually gets seen) + this._viewportLoc = { 'x': 0, 'y': 0, 'w': this._target.width, 'h': this._target.height }; + + // The hidden canvas, where we do the actual rendering + this._backbuffer = document.createElement('canvas'); + this._drawCtx = this._backbuffer.getContext('2d'); + + this._damageBounds = { left: 0, top: 0, + right: this._backbuffer.width, + bottom: this._backbuffer.height }; + + Log.Debug("User Agent: " + navigator.userAgent); + + Log.Debug("<< Display.constructor"); + + // ===== PROPERTIES ===== + + this._scale = 1.0; + this._clipViewport = false; + } + + // ===== PROPERTIES ===== + + get scale() { return this._scale; } + set scale(scale) { + this._rescale(scale); + } + + get clipViewport() { return this._clipViewport; } + set clipViewport(viewport) { + this._clipViewport = viewport; + // May need to readjust the viewport dimensions + const vp = this._viewportLoc; + this.viewportChangeSize(vp.w, vp.h); + this.viewportChangePos(0, 0); + } + + get width() { + return this._fbWidth; + } + + get height() { + return this._fbHeight; + } + + // ===== PUBLIC METHODS ===== + + viewportChangePos(deltaX, deltaY) { + const vp = this._viewportLoc; + deltaX = Math.floor(deltaX); + deltaY = Math.floor(deltaY); + + if (!this._clipViewport) { + deltaX = -vp.w; // clamped later of out of bounds + deltaY = -vp.h; + } + + const vx2 = vp.x + vp.w - 1; + const vy2 = vp.y + vp.h - 1; + + // Position change + + if (deltaX < 0 && vp.x + deltaX < 0) { + deltaX = -vp.x; + } + if (vx2 + deltaX >= this._fbWidth) { + deltaX -= vx2 + deltaX - this._fbWidth + 1; + } + + if (vp.y + deltaY < 0) { + deltaY = -vp.y; + } + if (vy2 + deltaY >= this._fbHeight) { + deltaY -= (vy2 + deltaY - this._fbHeight + 1); + } + + if (deltaX === 0 && deltaY === 0) { + return; + } + Log.Debug("viewportChange deltaX: " + deltaX + ", deltaY: " + deltaY); + + vp.x += deltaX; + vp.y += deltaY; + + this._damage(vp.x, vp.y, vp.w, vp.h); + + this.flip(); + } + + viewportChangeSize(width, height) { + + if (!this._clipViewport || + typeof(width) === "undefined" || + typeof(height) === "undefined") { + + Log.Debug("Setting viewport to full display region"); + width = this._fbWidth; + height = this._fbHeight; + } + + width = Math.floor(width); + height = Math.floor(height); + + if (width > this._fbWidth) { + width = this._fbWidth; + } + if (height > this._fbHeight) { + height = this._fbHeight; + } + + const vp = this._viewportLoc; + if (vp.w !== width || vp.h !== height) { + vp.w = width; + vp.h = height; + + const canvas = this._target; + canvas.width = width; + canvas.height = height; + + // The position might need to be updated if we've grown + this.viewportChangePos(0, 0); + + this._damage(vp.x, vp.y, vp.w, vp.h); + this.flip(); + + // Update the visible size of the target canvas + this._rescale(this._scale); + } + } + + absX(x) { + if (this._scale === 0) { + return 0; + } + return toSigned32bit(x / this._scale + this._viewportLoc.x); + } + + absY(y) { + if (this._scale === 0) { + return 0; + } + return toSigned32bit(y / this._scale + this._viewportLoc.y); + } + + resize(width, height) { + this._prevDrawStyle = ""; + + this._fbWidth = width; + this._fbHeight = height; + + const canvas = this._backbuffer; + if (canvas.width !== width || canvas.height !== height) { + + // We have to save the canvas data since changing the size will clear it + let saveImg = null; + if (canvas.width > 0 && canvas.height > 0) { + saveImg = this._drawCtx.getImageData(0, 0, canvas.width, canvas.height); + } + + if (canvas.width !== width) { + canvas.width = width; + } + if (canvas.height !== height) { + canvas.height = height; + } + + if (saveImg) { + this._drawCtx.putImageData(saveImg, 0, 0); + } + } + + // Readjust the viewport as it may be incorrectly sized + // and positioned + const vp = this._viewportLoc; + this.viewportChangeSize(vp.w, vp.h); + this.viewportChangePos(0, 0); + } + + getImageData() { + return this._drawCtx.getImageData(0, 0, this.width, this.height); + } + + toDataURL(type, encoderOptions) { + return this._backbuffer.toDataURL(type, encoderOptions); + } + + toBlob(callback, type, quality) { + return this._backbuffer.toBlob(callback, type, quality); + } + + // Track what parts of the visible canvas that need updating + _damage(x, y, w, h) { + if (x < this._damageBounds.left) { + this._damageBounds.left = x; + } + if (y < this._damageBounds.top) { + this._damageBounds.top = y; + } + if ((x + w) > this._damageBounds.right) { + this._damageBounds.right = x + w; + } + if ((y + h) > this._damageBounds.bottom) { + this._damageBounds.bottom = y + h; + } + } + + // Update the visible canvas with the contents of the + // rendering canvas + flip(fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ + 'type': 'flip' + }); + } else { + let x = this._damageBounds.left; + let y = this._damageBounds.top; + let w = this._damageBounds.right - x; + let h = this._damageBounds.bottom - y; + + let vx = x - this._viewportLoc.x; + let vy = y - this._viewportLoc.y; + + if (vx < 0) { + w += vx; + x -= vx; + vx = 0; + } + if (vy < 0) { + h += vy; + y -= vy; + vy = 0; + } + + if ((vx + w) > this._viewportLoc.w) { + w = this._viewportLoc.w - vx; + } + if ((vy + h) > this._viewportLoc.h) { + h = this._viewportLoc.h - vy; + } + + if ((w > 0) && (h > 0)) { + // FIXME: We may need to disable image smoothing here + // as well (see copyImage()), but we haven't + // noticed any problem yet. + this._targetCtx.drawImage(this._backbuffer, + x, y, w, h, + vx, vy, w, h); + } + + this._damageBounds.left = this._damageBounds.top = 65535; + this._damageBounds.right = this._damageBounds.bottom = 0; + } + } + + pending() { + return this._renderQ.length > 0; + } + + flush() { + if (this._renderQ.length === 0) { + return Promise.resolve(); + } else { + if (this._flushPromise === null) { + this._flushPromise = new Promise((resolve) => { + this._flushResolve = resolve; + }); + } + return this._flushPromise; + } + } + + fillRect(x, y, width, height, color, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ + 'type': 'fill', + 'x': x, + 'y': y, + 'width': width, + 'height': height, + 'color': color + }); + } else { + this._setFillColor(color); + this._drawCtx.fillRect(x, y, width, height); + this._damage(x, y, width, height); + } + } + + copyImage(oldX, oldY, newX, newY, w, h, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ + 'type': 'copy', + 'oldX': oldX, + 'oldY': oldY, + 'x': newX, + 'y': newY, + 'width': w, + 'height': h, + }); + } else { + // Due to this bug among others [1] we need to disable the image-smoothing to + // avoid getting a blur effect when copying data. + // + // 1. https://bugzilla.mozilla.org/show_bug.cgi?id=1194719 + // + // We need to set these every time since all properties are reset + // when the the size is changed + this._drawCtx.mozImageSmoothingEnabled = false; + this._drawCtx.webkitImageSmoothingEnabled = false; + this._drawCtx.msImageSmoothingEnabled = false; + this._drawCtx.imageSmoothingEnabled = false; + + this._drawCtx.drawImage(this._backbuffer, + oldX, oldY, w, h, + newX, newY, w, h); + this._damage(newX, newY, w, h); + } + } + + imageRect(x, y, width, height, mime, arr) { + /* The internal logic cannot handle empty images, so bail early */ + if ((width === 0) || (height === 0)) { + return; + } + + const img = new Image(); + img.src = "data: " + mime + ";base64," + Base64.encode(arr); + + this._renderQPush({ + 'type': 'img', + 'img': img, + 'x': x, + 'y': y, + 'width': width, + 'height': height + }); + } + + videoFrame(x, y, width, height, frame) { + this._renderQPush({ + 'type': 'frame', + 'frame': frame, + 'x': x, + 'y': y, + 'width': width, + 'height': height + }); + } + + blitImage(x, y, width, height, arr, offset, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + // NB(directxman12): it's technically more performant here to use preallocated arrays, + // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, + // this probably isn't getting called *nearly* as much + const newArr = new Uint8Array(width * height * 4); + newArr.set(new Uint8Array(arr.buffer, 0, newArr.length)); + this._renderQPush({ + 'type': 'blit', + 'data': newArr, + 'x': x, + 'y': y, + 'width': width, + 'height': height, + }); + } else { + // NB(directxman12): arr must be an Type Array view + let data = new Uint8ClampedArray(arr.buffer, + arr.byteOffset + offset, + width * height * 4); + let img = new ImageData(data, width, height); + this._drawCtx.putImageData(img, x, y); + this._damage(x, y, width, height); + } + } + + drawImage(img, ...args) { + this._drawCtx.drawImage(img, ...args); + + if (args.length <= 4) { + const [x, y] = args; + this._damage(x, y, img.width, img.height); + } else { + const [,, sw, sh, dx, dy] = args; + this._damage(dx, dy, sw, sh); + } + } + + autoscale(containerWidth, containerHeight) { + let scaleRatio; + + if (containerWidth === 0 || containerHeight === 0) { + scaleRatio = 0; + + } else { + + const vp = this._viewportLoc; + const targetAspectRatio = containerWidth / containerHeight; + const fbAspectRatio = vp.w / vp.h; + + if (fbAspectRatio >= targetAspectRatio) { + scaleRatio = containerWidth / vp.w; + } else { + scaleRatio = containerHeight / vp.h; + } + } + + this._rescale(scaleRatio); + } + + // ===== PRIVATE METHODS ===== + + _rescale(factor) { + this._scale = factor; + const vp = this._viewportLoc; + + // NB(directxman12): If you set the width directly, or set the + // style width to a number, the canvas is cleared. + // However, if you set the style width to a string + // ('NNNpx'), the canvas is scaled without clearing. + const width = factor * vp.w + 'px'; + const height = factor * vp.h + 'px'; + + if ((this._target.style.width !== width) || + (this._target.style.height !== height)) { + this._target.style.width = width; + this._target.style.height = height; + } + } + + _setFillColor(color) { + const newStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')'; + if (newStyle !== this._prevDrawStyle) { + this._drawCtx.fillStyle = newStyle; + this._prevDrawStyle = newStyle; + } + } + + _renderQPush(action) { + this._renderQ.push(action); + if (this._renderQ.length === 1) { + // If this can be rendered immediately it will be, otherwise + // the scanner will wait for the relevant event + this._scanRenderQ(); + } + } + + _resumeRenderQ() { + // "this" is the object that is ready, not the + // display object + this.removeEventListener('load', this._noVNCDisplay._resumeRenderQ); + this._noVNCDisplay._scanRenderQ(); + } + + _scanRenderQ() { + let ready = true; + while (ready && this._renderQ.length > 0) { + const a = this._renderQ[0]; + switch (a.type) { + case 'flip': + this.flip(true); + break; + case 'copy': + this.copyImage(a.oldX, a.oldY, a.x, a.y, a.width, a.height, true); + break; + case 'fill': + this.fillRect(a.x, a.y, a.width, a.height, a.color, true); + break; + case 'blit': + this.blitImage(a.x, a.y, a.width, a.height, a.data, 0, true); + break; + case 'img': + if (a.img.complete) { + if (a.img.width !== a.width || a.img.height !== a.height) { + Log.Error("Decoded image has incorrect dimensions. Got " + + a.img.width + "x" + a.img.height + ". Expected " + + a.width + "x" + a.height + "."); + return; + } + this.drawImage(a.img, a.x, a.y); + // This helps the browser free the memory right + // away, rather than ballooning + a.img.src = ""; + } else { + a.img._noVNCDisplay = this; + a.img.addEventListener('load', this._resumeRenderQ); + // We need to wait for this image to 'load' + // to keep things in-order + ready = false; + } + break; + case 'frame': + if (a.frame.ready) { + // The encoded frame may be larger than the rect due to + // limitations of the encoder, so we need to crop the + // frame. + let frame = a.frame.frame; + if (frame.codedWidth < a.width || frame.codedHeight < a.height) { + Log.Warn("Decoded video frame does not cover its full rectangle area. Expecting at least " + + a.width + "x" + a.height + " but got " + + frame.codedWidth + "x" + frame.codedHeight); + } + const sx = 0; + const sy = 0; + const sw = a.width; + const sh = a.height; + const dx = a.x; + const dy = a.y; + const dw = sw; + const dh = sh; + this.drawImage(frame, sx, sy, sw, sh, dx, dy, dw, dh); + frame.close(); + } else { + let display = this; + a.frame.promise.then(() => { + display._scanRenderQ(); + }); + ready = false; + } + break; + } + + if (ready) { + this._renderQ.shift(); + } + } + + if (this._renderQ.length === 0 && + this._flushPromise !== null) { + this._flushResolve(); + this._flushPromise = null; + this._flushResolve = null; + } + } +} diff --git a/engine/static/vendor/novnc/core/encodings.js b/engine/static/vendor/novnc/core/encodings.js new file mode 100644 index 00000000..7afcb17f --- /dev/null +++ b/engine/static/vendor/novnc/core/encodings.js @@ -0,0 +1,54 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +export const encodings = { + encodingRaw: 0, + encodingCopyRect: 1, + encodingRRE: 2, + encodingHextile: 5, + encodingZlib: 6, + encodingTight: 7, + encodingZRLE: 16, + encodingTightPNG: -260, + encodingJPEG: 21, + encodingH264: 50, + + pseudoEncodingQualityLevel9: -23, + pseudoEncodingQualityLevel0: -32, + pseudoEncodingDesktopSize: -223, + pseudoEncodingLastRect: -224, + pseudoEncodingCursor: -239, + pseudoEncodingQEMUExtendedKeyEvent: -258, + pseudoEncodingQEMULedEvent: -261, + pseudoEncodingDesktopName: -307, + pseudoEncodingExtendedDesktopSize: -308, + pseudoEncodingXvp: -309, + pseudoEncodingFence: -312, + pseudoEncodingContinuousUpdates: -313, + pseudoEncodingExtendedMouseButtons: -316, + pseudoEncodingCompressLevel9: -247, + pseudoEncodingCompressLevel0: -256, + pseudoEncodingVMwareCursor: 0x574d5664, + pseudoEncodingExtendedClipboard: 0xc0a1e5ce +}; + +export function encodingName(num) { + switch (num) { + case encodings.encodingRaw: return "Raw"; + case encodings.encodingCopyRect: return "CopyRect"; + case encodings.encodingRRE: return "RRE"; + case encodings.encodingHextile: return "Hextile"; + case encodings.encodingZlib: return "Zlib"; + case encodings.encodingTight: return "Tight"; + case encodings.encodingZRLE: return "ZRLE"; + case encodings.encodingTightPNG: return "TightPNG"; + case encodings.encodingJPEG: return "JPEG"; + case encodings.encodingH264: return "H.264"; + default: return "[unknown encoding " + num + "]"; + } +} diff --git a/engine/static/vendor/novnc/core/inflator.js b/engine/static/vendor/novnc/core/inflator.js new file mode 100644 index 00000000..7ef47f13 --- /dev/null +++ b/engine/static/vendor/novnc/core/inflator.js @@ -0,0 +1,65 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +import { inflateInit, inflate, inflateReset } from "../vendor/pako/lib/zlib/inflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; + +export default class Inflate { + constructor() { + this.strm = new ZStream(); + this.chunkSize = 1024 * 10 * 10; + this.strm.output = new Uint8Array(this.chunkSize); + + inflateInit(this.strm); + } + + setInput(data) { + if (!data) { + //FIXME: flush remaining data. + /* eslint-disable camelcase */ + this.strm.input = null; + this.strm.avail_in = 0; + this.strm.next_in = 0; + } else { + this.strm.input = data; + this.strm.avail_in = this.strm.input.length; + this.strm.next_in = 0; + /* eslint-enable camelcase */ + } + } + + inflate(expected) { + // resize our output buffer if it's too small + // (we could just use multiple chunks, but that would cause an extra + // allocation each time to flatten the chunks) + if (expected > this.chunkSize) { + this.chunkSize = expected; + this.strm.output = new Uint8Array(this.chunkSize); + } + + /* eslint-disable camelcase */ + this.strm.next_out = 0; + this.strm.avail_out = expected; + /* eslint-enable camelcase */ + + let ret = inflate(this.strm, 0); // Flush argument not used. + if (ret < 0) { + throw new Error("zlib inflate failed"); + } + + if (this.strm.next_out != expected) { + throw new Error("Incomplete zlib block"); + } + + return new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + } + + reset() { + inflateReset(this.strm); + } +} diff --git a/engine/static/vendor/novnc/core/input/domkeytable.js b/engine/static/vendor/novnc/core/input/domkeytable.js new file mode 100644 index 00000000..9e599f74 --- /dev/null +++ b/engine/static/vendor/novnc/core/input/domkeytable.js @@ -0,0 +1,311 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +import KeyTable from "./keysym.js"; + +/* + * Mapping between HTML key values and VNC/X11 keysyms for "special" + * keys that cannot be handled via their Unicode codepoint. + * + * See https://www.w3.org/TR/uievents-key/ for possible values. + */ + +const DOMKeyTable = {}; + +function addStandard(key, standard) { + if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); + DOMKeyTable[key] = [standard, standard, standard, standard]; +} + +function addLeftRight(key, left, right) { + if (left === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (right === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); + DOMKeyTable[key] = [left, left, right, left]; +} + +function addNumpad(key, standard, numpad) { + if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (numpad === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); + DOMKeyTable[key] = [standard, standard, standard, numpad]; +} + +// 3.2. Modifier Keys + +addLeftRight("Alt", KeyTable.XK_Alt_L, KeyTable.XK_Alt_R); +addStandard("AltGraph", KeyTable.XK_ISO_Level3_Shift); +addStandard("CapsLock", KeyTable.XK_Caps_Lock); +addLeftRight("Control", KeyTable.XK_Control_L, KeyTable.XK_Control_R); +// - Fn +// - FnLock +addLeftRight("Meta", KeyTable.XK_Super_L, KeyTable.XK_Super_R); +addStandard("NumLock", KeyTable.XK_Num_Lock); +addStandard("ScrollLock", KeyTable.XK_Scroll_Lock); +addLeftRight("Shift", KeyTable.XK_Shift_L, KeyTable.XK_Shift_R); +// - Symbol +// - SymbolLock +// - Hyper +// - Super + +// 3.3. Whitespace Keys + +addNumpad("Enter", KeyTable.XK_Return, KeyTable.XK_KP_Enter); +addStandard("Tab", KeyTable.XK_Tab); +addNumpad(" ", KeyTable.XK_space, KeyTable.XK_KP_Space); + +// 3.4. Navigation Keys + +addNumpad("ArrowDown", KeyTable.XK_Down, KeyTable.XK_KP_Down); +addNumpad("ArrowLeft", KeyTable.XK_Left, KeyTable.XK_KP_Left); +addNumpad("ArrowRight", KeyTable.XK_Right, KeyTable.XK_KP_Right); +addNumpad("ArrowUp", KeyTable.XK_Up, KeyTable.XK_KP_Up); +addNumpad("End", KeyTable.XK_End, KeyTable.XK_KP_End); +addNumpad("Home", KeyTable.XK_Home, KeyTable.XK_KP_Home); +addNumpad("PageDown", KeyTable.XK_Next, KeyTable.XK_KP_Next); +addNumpad("PageUp", KeyTable.XK_Prior, KeyTable.XK_KP_Prior); + +// 3.5. Editing Keys + +addStandard("Backspace", KeyTable.XK_BackSpace); +// Browsers send "Clear" for the numpad 5 without NumLock because +// Windows uses VK_Clear for that key. But Unix expects KP_Begin for +// that scenario. +addNumpad("Clear", KeyTable.XK_Clear, KeyTable.XK_KP_Begin); +addStandard("Copy", KeyTable.XF86XK_Copy); +// - CrSel +addStandard("Cut", KeyTable.XF86XK_Cut); +addNumpad("Delete", KeyTable.XK_Delete, KeyTable.XK_KP_Delete); +// - EraseEof +// - ExSel +addNumpad("Insert", KeyTable.XK_Insert, KeyTable.XK_KP_Insert); +addStandard("Paste", KeyTable.XF86XK_Paste); +addStandard("Redo", KeyTable.XK_Redo); +addStandard("Undo", KeyTable.XK_Undo); + +// 3.6. UI Keys + +// - Accept +// - Again (could just be XK_Redo) +// - Attn +addStandard("Cancel", KeyTable.XK_Cancel); +addStandard("ContextMenu", KeyTable.XK_Menu); +addStandard("Escape", KeyTable.XK_Escape); +addStandard("Execute", KeyTable.XK_Execute); +addStandard("Find", KeyTable.XK_Find); +addStandard("Help", KeyTable.XK_Help); +addStandard("Pause", KeyTable.XK_Pause); +// - Play +// - Props +addStandard("Select", KeyTable.XK_Select); +addStandard("ZoomIn", KeyTable.XF86XK_ZoomIn); +addStandard("ZoomOut", KeyTable.XF86XK_ZoomOut); + +// 3.7. Device Keys + +addStandard("BrightnessDown", KeyTable.XF86XK_MonBrightnessDown); +addStandard("BrightnessUp", KeyTable.XF86XK_MonBrightnessUp); +addStandard("Eject", KeyTable.XF86XK_Eject); +addStandard("LogOff", KeyTable.XF86XK_LogOff); +addStandard("Power", KeyTable.XF86XK_PowerOff); +addStandard("PowerOff", KeyTable.XF86XK_PowerDown); +addStandard("PrintScreen", KeyTable.XK_Print); +addStandard("Hibernate", KeyTable.XF86XK_Hibernate); +addStandard("Standby", KeyTable.XF86XK_Standby); +addStandard("WakeUp", KeyTable.XF86XK_WakeUp); + +// 3.8. IME and Composition Keys + +addStandard("AllCandidates", KeyTable.XK_MultipleCandidate); +addStandard("Alphanumeric", KeyTable.XK_Eisu_toggle); +addStandard("CodeInput", KeyTable.XK_Codeinput); +addStandard("Compose", KeyTable.XK_Multi_key); +addStandard("Convert", KeyTable.XK_Henkan); +// - Dead +// - FinalMode +addStandard("GroupFirst", KeyTable.XK_ISO_First_Group); +addStandard("GroupLast", KeyTable.XK_ISO_Last_Group); +addStandard("GroupNext", KeyTable.XK_ISO_Next_Group); +addStandard("GroupPrevious", KeyTable.XK_ISO_Prev_Group); +// - ModeChange (XK_Mode_switch is often used for AltGr) +// - NextCandidate +addStandard("NonConvert", KeyTable.XK_Muhenkan); +addStandard("PreviousCandidate", KeyTable.XK_PreviousCandidate); +// - Process +addStandard("SingleCandidate", KeyTable.XK_SingleCandidate); +addStandard("HangulMode", KeyTable.XK_Hangul); +addStandard("HanjaMode", KeyTable.XK_Hangul_Hanja); +addStandard("JunjaMode", KeyTable.XK_Hangul_Jeonja); +addStandard("Eisu", KeyTable.XK_Eisu_toggle); +addStandard("Hankaku", KeyTable.XK_Hankaku); +addStandard("Hiragana", KeyTable.XK_Hiragana); +addStandard("HiraganaKatakana", KeyTable.XK_Hiragana_Katakana); +addStandard("KanaMode", KeyTable.XK_Kana_Shift); // could also be _Kana_Lock +addStandard("KanjiMode", KeyTable.XK_Kanji); +addStandard("Katakana", KeyTable.XK_Katakana); +addStandard("Romaji", KeyTable.XK_Romaji); +addStandard("Zenkaku", KeyTable.XK_Zenkaku); +addStandard("ZenkakuHankaku", KeyTable.XK_Zenkaku_Hankaku); + +// 3.9. General-Purpose Function Keys + +addStandard("F1", KeyTable.XK_F1); +addStandard("F2", KeyTable.XK_F2); +addStandard("F3", KeyTable.XK_F3); +addStandard("F4", KeyTable.XK_F4); +addStandard("F5", KeyTable.XK_F5); +addStandard("F6", KeyTable.XK_F6); +addStandard("F7", KeyTable.XK_F7); +addStandard("F8", KeyTable.XK_F8); +addStandard("F9", KeyTable.XK_F9); +addStandard("F10", KeyTable.XK_F10); +addStandard("F11", KeyTable.XK_F11); +addStandard("F12", KeyTable.XK_F12); +addStandard("F13", KeyTable.XK_F13); +addStandard("F14", KeyTable.XK_F14); +addStandard("F15", KeyTable.XK_F15); +addStandard("F16", KeyTable.XK_F16); +addStandard("F17", KeyTable.XK_F17); +addStandard("F18", KeyTable.XK_F18); +addStandard("F19", KeyTable.XK_F19); +addStandard("F20", KeyTable.XK_F20); +addStandard("F21", KeyTable.XK_F21); +addStandard("F22", KeyTable.XK_F22); +addStandard("F23", KeyTable.XK_F23); +addStandard("F24", KeyTable.XK_F24); +addStandard("F25", KeyTable.XK_F25); +addStandard("F26", KeyTable.XK_F26); +addStandard("F27", KeyTable.XK_F27); +addStandard("F28", KeyTable.XK_F28); +addStandard("F29", KeyTable.XK_F29); +addStandard("F30", KeyTable.XK_F30); +addStandard("F31", KeyTable.XK_F31); +addStandard("F32", KeyTable.XK_F32); +addStandard("F33", KeyTable.XK_F33); +addStandard("F34", KeyTable.XK_F34); +addStandard("F35", KeyTable.XK_F35); +// - Soft1... + +// 3.10. Multimedia Keys + +// - ChannelDown +// - ChannelUp +addStandard("Close", KeyTable.XF86XK_Close); +addStandard("MailForward", KeyTable.XF86XK_MailForward); +addStandard("MailReply", KeyTable.XF86XK_Reply); +addStandard("MailSend", KeyTable.XF86XK_Send); +// - MediaClose +addStandard("MediaFastForward", KeyTable.XF86XK_AudioForward); +addStandard("MediaPause", KeyTable.XF86XK_AudioPause); +addStandard("MediaPlay", KeyTable.XF86XK_AudioPlay); +// - MediaPlayPause +addStandard("MediaRecord", KeyTable.XF86XK_AudioRecord); +addStandard("MediaRewind", KeyTable.XF86XK_AudioRewind); +addStandard("MediaStop", KeyTable.XF86XK_AudioStop); +addStandard("MediaTrackNext", KeyTable.XF86XK_AudioNext); +addStandard("MediaTrackPrevious", KeyTable.XF86XK_AudioPrev); +addStandard("New", KeyTable.XF86XK_New); +addStandard("Open", KeyTable.XF86XK_Open); +addStandard("Print", KeyTable.XK_Print); +addStandard("Save", KeyTable.XF86XK_Save); +addStandard("SpellCheck", KeyTable.XF86XK_Spell); + +// 3.11. Multimedia Numpad Keys + +// - Key11 +// - Key12 + +// 3.12. Audio Keys + +// - AudioBalanceLeft +// - AudioBalanceRight +// - AudioBassBoostDown +// - AudioBassBoostToggle +// - AudioBassBoostUp +// - AudioFaderFront +// - AudioFaderRear +// - AudioSurroundModeNext +// - AudioTrebleDown +// - AudioTrebleUp +addStandard("AudioVolumeDown", KeyTable.XF86XK_AudioLowerVolume); +addStandard("AudioVolumeUp", KeyTable.XF86XK_AudioRaiseVolume); +addStandard("AudioVolumeMute", KeyTable.XF86XK_AudioMute); +// - MicrophoneToggle +// - MicrophoneVolumeDown +// - MicrophoneVolumeUp +addStandard("MicrophoneVolumeMute", KeyTable.XF86XK_AudioMicMute); + +// 3.13. Speech Keys + +// - SpeechCorrectionList +// - SpeechInputToggle + +// 3.14. Application Keys + +addStandard("LaunchApplication1", KeyTable.XF86XK_MyComputer); +addStandard("LaunchApplication2", KeyTable.XF86XK_Calculator); +addStandard("LaunchCalendar", KeyTable.XF86XK_Calendar); +// - LaunchContacts +addStandard("LaunchMail", KeyTable.XF86XK_Mail); +addStandard("LaunchMediaPlayer", KeyTable.XF86XK_AudioMedia); +addStandard("LaunchMusicPlayer", KeyTable.XF86XK_Music); +addStandard("LaunchPhone", KeyTable.XF86XK_Phone); +addStandard("LaunchScreenSaver", KeyTable.XF86XK_ScreenSaver); +addStandard("LaunchSpreadsheet", KeyTable.XF86XK_Excel); +addStandard("LaunchWebBrowser", KeyTable.XF86XK_WWW); +addStandard("LaunchWebCam", KeyTable.XF86XK_WebCam); +addStandard("LaunchWordProcessor", KeyTable.XF86XK_Word); + +// 3.15. Browser Keys + +addStandard("BrowserBack", KeyTable.XF86XK_Back); +addStandard("BrowserFavorites", KeyTable.XF86XK_Favorites); +addStandard("BrowserForward", KeyTable.XF86XK_Forward); +addStandard("BrowserHome", KeyTable.XF86XK_HomePage); +addStandard("BrowserRefresh", KeyTable.XF86XK_Refresh); +addStandard("BrowserSearch", KeyTable.XF86XK_Search); +addStandard("BrowserStop", KeyTable.XF86XK_Stop); + +// 3.16. Mobile Phone Keys + +// - A whole bunch... + +// 3.17. TV Keys + +// - A whole bunch... + +// 3.18. Media Controller Keys + +// - A whole bunch... +addStandard("Dimmer", KeyTable.XF86XK_BrightnessAdjust); +addStandard("MediaAudioTrack", KeyTable.XF86XK_AudioCycleTrack); +addStandard("RandomToggle", KeyTable.XF86XK_AudioRandomPlay); +addStandard("SplitScreenToggle", KeyTable.XF86XK_SplitScreen); +addStandard("Subtitle", KeyTable.XF86XK_Subtitle); +addStandard("VideoModeNext", KeyTable.XF86XK_Next_VMode); + +// Extra: Numpad + +addNumpad("=", KeyTable.XK_equal, KeyTable.XK_KP_Equal); +addNumpad("+", KeyTable.XK_plus, KeyTable.XK_KP_Add); +addNumpad("-", KeyTable.XK_minus, KeyTable.XK_KP_Subtract); +addNumpad("*", KeyTable.XK_asterisk, KeyTable.XK_KP_Multiply); +addNumpad("/", KeyTable.XK_slash, KeyTable.XK_KP_Divide); +addNumpad(".", KeyTable.XK_period, KeyTable.XK_KP_Decimal); +addNumpad(",", KeyTable.XK_comma, KeyTable.XK_KP_Separator); +addNumpad("0", KeyTable.XK_0, KeyTable.XK_KP_0); +addNumpad("1", KeyTable.XK_1, KeyTable.XK_KP_1); +addNumpad("2", KeyTable.XK_2, KeyTable.XK_KP_2); +addNumpad("3", KeyTable.XK_3, KeyTable.XK_KP_3); +addNumpad("4", KeyTable.XK_4, KeyTable.XK_KP_4); +addNumpad("5", KeyTable.XK_5, KeyTable.XK_KP_5); +addNumpad("6", KeyTable.XK_6, KeyTable.XK_KP_6); +addNumpad("7", KeyTable.XK_7, KeyTable.XK_KP_7); +addNumpad("8", KeyTable.XK_8, KeyTable.XK_KP_8); +addNumpad("9", KeyTable.XK_9, KeyTable.XK_KP_9); + +export default DOMKeyTable; diff --git a/engine/static/vendor/novnc/core/input/fixedkeys.js b/engine/static/vendor/novnc/core/input/fixedkeys.js new file mode 100644 index 00000000..6a922158 --- /dev/null +++ b/engine/static/vendor/novnc/core/input/fixedkeys.js @@ -0,0 +1,129 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +/* + * Fallback mapping between HTML key codes (physical keys) and + * HTML key values. This only works for keys that don't vary + * between layouts. We also omit those who manage fine by mapping the + * Unicode representation. + * + * See https://www.w3.org/TR/uievents-code/ for possible codes. + * See https://www.w3.org/TR/uievents-key/ for possible values. + */ + +/* eslint-disable key-spacing */ + +export default { + +// 3.1.1.1. Writing System Keys + + 'Backspace': 'Backspace', + +// 3.1.1.2. Functional Keys + + 'AltLeft': 'Alt', + 'AltRight': 'Alt', // This could also be 'AltGraph' + 'CapsLock': 'CapsLock', + 'ContextMenu': 'ContextMenu', + 'ControlLeft': 'Control', + 'ControlRight': 'Control', + 'Enter': 'Enter', + 'MetaLeft': 'Meta', + 'MetaRight': 'Meta', + 'ShiftLeft': 'Shift', + 'ShiftRight': 'Shift', + 'Tab': 'Tab', + // FIXME: Japanese/Korean keys + +// 3.1.2. Control Pad Section + + 'Delete': 'Delete', + 'End': 'End', + 'Help': 'Help', + 'Home': 'Home', + 'Insert': 'Insert', + 'PageDown': 'PageDown', + 'PageUp': 'PageUp', + +// 3.1.3. Arrow Pad Section + + 'ArrowDown': 'ArrowDown', + 'ArrowLeft': 'ArrowLeft', + 'ArrowRight': 'ArrowRight', + 'ArrowUp': 'ArrowUp', + +// 3.1.4. Numpad Section + + 'NumLock': 'NumLock', + 'NumpadBackspace': 'Backspace', + 'NumpadClear': 'Clear', + +// 3.1.5. Function Section + + 'Escape': 'Escape', + 'F1': 'F1', + 'F2': 'F2', + 'F3': 'F3', + 'F4': 'F4', + 'F5': 'F5', + 'F6': 'F6', + 'F7': 'F7', + 'F8': 'F8', + 'F9': 'F9', + 'F10': 'F10', + 'F11': 'F11', + 'F12': 'F12', + 'F13': 'F13', + 'F14': 'F14', + 'F15': 'F15', + 'F16': 'F16', + 'F17': 'F17', + 'F18': 'F18', + 'F19': 'F19', + 'F20': 'F20', + 'F21': 'F21', + 'F22': 'F22', + 'F23': 'F23', + 'F24': 'F24', + 'F25': 'F25', + 'F26': 'F26', + 'F27': 'F27', + 'F28': 'F28', + 'F29': 'F29', + 'F30': 'F30', + 'F31': 'F31', + 'F32': 'F32', + 'F33': 'F33', + 'F34': 'F34', + 'F35': 'F35', + 'PrintScreen': 'PrintScreen', + 'ScrollLock': 'ScrollLock', + 'Pause': 'Pause', + +// 3.1.6. Media Keys + + 'BrowserBack': 'BrowserBack', + 'BrowserFavorites': 'BrowserFavorites', + 'BrowserForward': 'BrowserForward', + 'BrowserHome': 'BrowserHome', + 'BrowserRefresh': 'BrowserRefresh', + 'BrowserSearch': 'BrowserSearch', + 'BrowserStop': 'BrowserStop', + 'Eject': 'Eject', + 'LaunchApp1': 'LaunchMyComputer', + 'LaunchApp2': 'LaunchCalendar', + 'LaunchMail': 'LaunchMail', + 'MediaPlayPause': 'MediaPlay', + 'MediaStop': 'MediaStop', + 'MediaTrackNext': 'MediaTrackNext', + 'MediaTrackPrevious': 'MediaTrackPrevious', + 'Power': 'Power', + 'Sleep': 'Sleep', + 'AudioVolumeDown': 'AudioVolumeDown', + 'AudioVolumeMute': 'AudioVolumeMute', + 'AudioVolumeUp': 'AudioVolumeUp', + 'WakeUp': 'WakeUp', +}; diff --git a/engine/static/vendor/novnc/core/input/gesturehandler.js b/engine/static/vendor/novnc/core/input/gesturehandler.js new file mode 100644 index 00000000..b072e01d --- /dev/null +++ b/engine/static/vendor/novnc/core/input/gesturehandler.js @@ -0,0 +1,567 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +const GH_NOGESTURE = 0; +const GH_ONETAP = 1; +const GH_TWOTAP = 2; +const GH_THREETAP = 4; +const GH_DRAG = 8; +const GH_LONGPRESS = 16; +const GH_TWODRAG = 32; +const GH_PINCH = 64; + +const GH_INITSTATE = 127; + +const GH_MOVE_THRESHOLD = 50; +const GH_ANGLE_THRESHOLD = 90; // Degrees + +// Timeout when waiting for gestures (ms) +const GH_MULTITOUCH_TIMEOUT = 250; + +// Maximum time between press and release for a tap (ms) +const GH_TAP_TIMEOUT = 1000; + +// Timeout when waiting for longpress (ms) +const GH_LONGPRESS_TIMEOUT = 1000; + +// Timeout when waiting to decide between PINCH and TWODRAG (ms) +const GH_TWOTOUCH_TIMEOUT = 50; + +export default class GestureHandler { + constructor() { + this._target = null; + + this._state = GH_INITSTATE; + + this._tracked = []; + this._ignored = []; + + this._waitingRelease = false; + this._releaseStart = 0.0; + + this._longpressTimeoutId = null; + this._twoTouchTimeoutId = null; + + this._boundEventHandler = this._eventHandler.bind(this); + } + + attach(target) { + this.detach(); + + this._target = target; + this._target.addEventListener('touchstart', + this._boundEventHandler); + this._target.addEventListener('touchmove', + this._boundEventHandler); + this._target.addEventListener('touchend', + this._boundEventHandler); + this._target.addEventListener('touchcancel', + this._boundEventHandler); + } + + detach() { + if (!this._target) { + return; + } + + this._stopLongpressTimeout(); + this._stopTwoTouchTimeout(); + + this._target.removeEventListener('touchstart', + this._boundEventHandler); + this._target.removeEventListener('touchmove', + this._boundEventHandler); + this._target.removeEventListener('touchend', + this._boundEventHandler); + this._target.removeEventListener('touchcancel', + this._boundEventHandler); + this._target = null; + } + + _eventHandler(e) { + let fn; + + e.stopPropagation(); + e.preventDefault(); + + switch (e.type) { + case 'touchstart': + fn = this._touchStart; + break; + case 'touchmove': + fn = this._touchMove; + break; + case 'touchend': + case 'touchcancel': + fn = this._touchEnd; + break; + } + + for (let i = 0; i < e.changedTouches.length; i++) { + let touch = e.changedTouches[i]; + fn.call(this, touch.identifier, touch.clientX, touch.clientY); + } + } + + _touchStart(id, x, y) { + // Ignore any new touches if there is already an active gesture, + // or we're in a cleanup state + if (this._hasDetectedGesture() || (this._state === GH_NOGESTURE)) { + this._ignored.push(id); + return; + } + + // Did it take too long between touches that we should no longer + // consider this a single gesture? + if ((this._tracked.length > 0) && + ((Date.now() - this._tracked[0].started) > GH_MULTITOUCH_TIMEOUT)) { + this._state = GH_NOGESTURE; + this._ignored.push(id); + return; + } + + // If we're waiting for fingers to release then we should no longer + // recognize new touches + if (this._waitingRelease) { + this._state = GH_NOGESTURE; + this._ignored.push(id); + return; + } + + this._tracked.push({ + id: id, + started: Date.now(), + active: true, + firstX: x, + firstY: y, + lastX: x, + lastY: y, + angle: 0 + }); + + switch (this._tracked.length) { + case 1: + this._startLongpressTimeout(); + break; + + case 2: + this._state &= ~(GH_ONETAP | GH_DRAG | GH_LONGPRESS); + this._stopLongpressTimeout(); + break; + + case 3: + this._state &= ~(GH_TWOTAP | GH_TWODRAG | GH_PINCH); + break; + + default: + this._state = GH_NOGESTURE; + } + } + + _touchMove(id, x, y) { + let touch = this._tracked.find(t => t.id === id); + + // If this is an update for a touch we're not tracking, ignore it + if (touch === undefined) { + return; + } + + // Update the touches last position with the event coordinates + touch.lastX = x; + touch.lastY = y; + + let deltaX = x - touch.firstX; + let deltaY = y - touch.firstY; + + // Update angle when the touch has moved + if ((touch.firstX !== touch.lastX) || + (touch.firstY !== touch.lastY)) { + touch.angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI; + } + + if (!this._hasDetectedGesture()) { + // Ignore moves smaller than the minimum threshold + if (Math.hypot(deltaX, deltaY) < GH_MOVE_THRESHOLD) { + return; + } + + // Can't be a tap or long press as we've seen movement + this._state &= ~(GH_ONETAP | GH_TWOTAP | GH_THREETAP | GH_LONGPRESS); + this._stopLongpressTimeout(); + + if (this._tracked.length !== 1) { + this._state &= ~(GH_DRAG); + } + if (this._tracked.length !== 2) { + this._state &= ~(GH_TWODRAG | GH_PINCH); + } + + // We need to figure out which of our different two touch gestures + // this might be + if (this._tracked.length === 2) { + + // The other touch is the one where the id doesn't match + let prevTouch = this._tracked.find(t => t.id !== id); + + // How far the previous touch point has moved since start + let prevDeltaMove = Math.hypot(prevTouch.firstX - prevTouch.lastX, + prevTouch.firstY - prevTouch.lastY); + + // We know that the current touch moved far enough, + // but unless both touches moved further than their + // threshold we don't want to disqualify any gestures + if (prevDeltaMove > GH_MOVE_THRESHOLD) { + + // The angle difference between the direction of the touch points + let deltaAngle = Math.abs(touch.angle - prevTouch.angle); + deltaAngle = Math.abs(((deltaAngle + 180) % 360) - 180); + + // PINCH or TWODRAG can be eliminated depending on the angle + if (deltaAngle > GH_ANGLE_THRESHOLD) { + this._state &= ~GH_TWODRAG; + } else { + this._state &= ~GH_PINCH; + } + + if (this._isTwoTouchTimeoutRunning()) { + this._stopTwoTouchTimeout(); + } + } else if (!this._isTwoTouchTimeoutRunning()) { + // We can't determine the gesture right now, let's + // wait and see if more events are on their way + this._startTwoTouchTimeout(); + } + } + + if (!this._hasDetectedGesture()) { + return; + } + + this._pushEvent('gesturestart'); + } + + this._pushEvent('gesturemove'); + } + + _touchEnd(id, x, y) { + // Check if this is an ignored touch + if (this._ignored.indexOf(id) !== -1) { + // Remove this touch from ignored + this._ignored.splice(this._ignored.indexOf(id), 1); + + // And reset the state if there are no more touches + if ((this._ignored.length === 0) && + (this._tracked.length === 0)) { + this._state = GH_INITSTATE; + this._waitingRelease = false; + } + return; + } + + // We got a touchend before the timer triggered, + // this cannot result in a gesture anymore. + if (!this._hasDetectedGesture() && + this._isTwoTouchTimeoutRunning()) { + this._stopTwoTouchTimeout(); + this._state = GH_NOGESTURE; + } + + // Some gestures don't trigger until a touch is released + if (!this._hasDetectedGesture()) { + // Can't be a gesture that relies on movement + this._state &= ~(GH_DRAG | GH_TWODRAG | GH_PINCH); + // Or something that relies on more time + this._state &= ~GH_LONGPRESS; + this._stopLongpressTimeout(); + + if (!this._waitingRelease) { + this._releaseStart = Date.now(); + this._waitingRelease = true; + + // Can't be a tap that requires more touches than we current have + switch (this._tracked.length) { + case 1: + this._state &= ~(GH_TWOTAP | GH_THREETAP); + break; + + case 2: + this._state &= ~(GH_ONETAP | GH_THREETAP); + break; + } + } + } + + // Waiting for all touches to release? (i.e. some tap) + if (this._waitingRelease) { + // Were all touches released at roughly the same time? + if ((Date.now() - this._releaseStart) > GH_MULTITOUCH_TIMEOUT) { + this._state = GH_NOGESTURE; + } + + // Did too long time pass between press and release? + if (this._tracked.some(t => (Date.now() - t.started) > GH_TAP_TIMEOUT)) { + this._state = GH_NOGESTURE; + } + + let touch = this._tracked.find(t => t.id === id); + touch.active = false; + + // Are we still waiting for more releases? + if (this._hasDetectedGesture()) { + this._pushEvent('gesturestart'); + } else { + // Have we reached a dead end? + if (this._state !== GH_NOGESTURE) { + return; + } + } + } + + if (this._hasDetectedGesture()) { + this._pushEvent('gestureend'); + } + + // Ignore any remaining touches until they are ended + for (let i = 0; i < this._tracked.length; i++) { + if (this._tracked[i].active) { + this._ignored.push(this._tracked[i].id); + } + } + this._tracked = []; + + this._state = GH_NOGESTURE; + + // Remove this touch from ignored if it's in there + if (this._ignored.indexOf(id) !== -1) { + this._ignored.splice(this._ignored.indexOf(id), 1); + } + + // We reset the state if ignored is empty + if ((this._ignored.length === 0)) { + this._state = GH_INITSTATE; + this._waitingRelease = false; + } + } + + _hasDetectedGesture() { + if (this._state === GH_NOGESTURE) { + return false; + } + // Check to see if the bitmask value is a power of 2 + // (i.e. only one bit set). If it is, we have a state. + if (this._state & (this._state - 1)) { + return false; + } + + // For taps we also need to have all touches released + // before we've fully detected the gesture + if (this._state & (GH_ONETAP | GH_TWOTAP | GH_THREETAP)) { + if (this._tracked.some(t => t.active)) { + return false; + } + } + + return true; + } + + _startLongpressTimeout() { + this._stopLongpressTimeout(); + this._longpressTimeoutId = setTimeout(() => this._longpressTimeout(), + GH_LONGPRESS_TIMEOUT); + } + + _stopLongpressTimeout() { + clearTimeout(this._longpressTimeoutId); + this._longpressTimeoutId = null; + } + + _longpressTimeout() { + if (this._hasDetectedGesture()) { + throw new Error("A longpress gesture failed, conflict with a different gesture"); + } + + this._state = GH_LONGPRESS; + this._pushEvent('gesturestart'); + } + + _startTwoTouchTimeout() { + this._stopTwoTouchTimeout(); + this._twoTouchTimeoutId = setTimeout(() => this._twoTouchTimeout(), + GH_TWOTOUCH_TIMEOUT); + } + + _stopTwoTouchTimeout() { + clearTimeout(this._twoTouchTimeoutId); + this._twoTouchTimeoutId = null; + } + + _isTwoTouchTimeoutRunning() { + return this._twoTouchTimeoutId !== null; + } + + _twoTouchTimeout() { + if (this._tracked.length === 0) { + throw new Error("A pinch or two drag gesture failed, no tracked touches"); + } + + // How far each touch point has moved since start + let avgM = this._getAverageMovement(); + let avgMoveH = Math.abs(avgM.x); + let avgMoveV = Math.abs(avgM.y); + + // The difference in the distance between where + // the touch points started and where they are now + let avgD = this._getAverageDistance(); + let deltaTouchDistance = Math.abs(Math.hypot(avgD.first.x, avgD.first.y) - + Math.hypot(avgD.last.x, avgD.last.y)); + + if ((avgMoveV < deltaTouchDistance) && + (avgMoveH < deltaTouchDistance)) { + this._state = GH_PINCH; + } else { + this._state = GH_TWODRAG; + } + + this._pushEvent('gesturestart'); + this._pushEvent('gesturemove'); + } + + _pushEvent(type) { + let detail = { type: this._stateToGesture(this._state) }; + + // For most gesture events the current (average) position is the + // most useful + let avg = this._getPosition(); + let pos = avg.last; + + // However we have a slight distance to detect gestures, so for the + // first gesture event we want to use the first positions we saw + if (type === 'gesturestart') { + pos = avg.first; + } + + // For these gestures, we always want the event coordinates + // to be where the gesture began, not the current touch location. + switch (this._state) { + case GH_TWODRAG: + case GH_PINCH: + pos = avg.first; + break; + } + + detail['clientX'] = pos.x; + detail['clientY'] = pos.y; + + // FIXME: other coordinates? + + // Some gestures also have a magnitude + if (this._state === GH_PINCH) { + let distance = this._getAverageDistance(); + if (type === 'gesturestart') { + detail['magnitudeX'] = distance.first.x; + detail['magnitudeY'] = distance.first.y; + } else { + detail['magnitudeX'] = distance.last.x; + detail['magnitudeY'] = distance.last.y; + } + } else if (this._state === GH_TWODRAG) { + if (type === 'gesturestart') { + detail['magnitudeX'] = 0.0; + detail['magnitudeY'] = 0.0; + } else { + let movement = this._getAverageMovement(); + detail['magnitudeX'] = movement.x; + detail['magnitudeY'] = movement.y; + } + } + + let gev = new CustomEvent(type, { detail: detail }); + this._target.dispatchEvent(gev); + } + + _stateToGesture(state) { + switch (state) { + case GH_ONETAP: + return 'onetap'; + case GH_TWOTAP: + return 'twotap'; + case GH_THREETAP: + return 'threetap'; + case GH_DRAG: + return 'drag'; + case GH_LONGPRESS: + return 'longpress'; + case GH_TWODRAG: + return 'twodrag'; + case GH_PINCH: + return 'pinch'; + } + + throw new Error("Unknown gesture state: " + state); + } + + _getPosition() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture position, no tracked touches"); + } + + let size = this._tracked.length; + let fx = 0, fy = 0, lx = 0, ly = 0; + + for (let i = 0; i < this._tracked.length; i++) { + fx += this._tracked[i].firstX; + fy += this._tracked[i].firstY; + lx += this._tracked[i].lastX; + ly += this._tracked[i].lastY; + } + + return { first: { x: fx / size, + y: fy / size }, + last: { x: lx / size, + y: ly / size } }; + } + + _getAverageMovement() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture movement, no tracked touches"); + } + + let totalH, totalV; + totalH = totalV = 0; + let size = this._tracked.length; + + for (let i = 0; i < this._tracked.length; i++) { + totalH += this._tracked[i].lastX - this._tracked[i].firstX; + totalV += this._tracked[i].lastY - this._tracked[i].firstY; + } + + return { x: totalH / size, + y: totalV / size }; + } + + _getAverageDistance() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture distance, no tracked touches"); + } + + // Distance between the first and last tracked touches + + let first = this._tracked[0]; + let last = this._tracked[this._tracked.length - 1]; + + let fdx = Math.abs(last.firstX - first.firstX); + let fdy = Math.abs(last.firstY - first.firstY); + + let ldx = Math.abs(last.lastX - first.lastX); + let ldy = Math.abs(last.lastY - first.lastY); + + return { first: { x: fdx, y: fdy }, + last: { x: ldx, y: ldy } }; + } +} diff --git a/engine/static/vendor/novnc/core/input/keyboard.js b/engine/static/vendor/novnc/core/input/keyboard.js new file mode 100644 index 00000000..3cc89174 --- /dev/null +++ b/engine/static/vendor/novnc/core/input/keyboard.js @@ -0,0 +1,294 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +import * as Log from '../util/logging.js'; +import { stopEvent } from '../util/events.js'; +import * as KeyboardUtil from "./util.js"; +import KeyTable from "./keysym.js"; +import * as browser from "../util/browser.js"; + +// +// Keyboard event handler +// + +export default class Keyboard { + constructor(target) { + this._target = target || null; + + this._keyDownList = {}; // List of depressed keys + // (even if they are happy) + this._altGrArmed = false; // Windows AltGr detection + + // keep these here so we can refer to them later + this._eventHandlers = { + 'keyup': this._handleKeyUp.bind(this), + 'keydown': this._handleKeyDown.bind(this), + 'blur': this._allKeysUp.bind(this), + }; + + // ===== EVENT HANDLERS ===== + + this.onkeyevent = () => {}; // Handler for key press/release + } + + // ===== PRIVATE METHODS ===== + + _sendKeyEvent(keysym, code, down, numlock = null, capslock = null) { + if (down) { + this._keyDownList[code] = keysym; + } else { + // Do we really think this key is down? + if (!(code in this._keyDownList)) { + return; + } + delete this._keyDownList[code]; + } + + Log.Debug("onkeyevent " + (down ? "down" : "up") + + ", keysym: " + keysym, ", code: " + code + + ", numlock: " + numlock + ", capslock: " + capslock); + this.onkeyevent(keysym, code, down, numlock, capslock); + } + + _getKeyCode(e) { + const code = KeyboardUtil.getKeycode(e); + if (code !== 'Unidentified') { + return code; + } + + // Unstable, but we don't have anything else to go on + if (e.keyCode) { + // 229 is used for composition events + if (e.keyCode !== 229) { + return 'Platform' + e.keyCode; + } + } + + // A precursor to the final DOM3 standard. Unfortunately it + // is not layout independent, so it is as bad as using keyCode + if (e.keyIdentifier) { + // Non-character key? + if (e.keyIdentifier.substr(0, 2) !== 'U+') { + return e.keyIdentifier; + } + + const codepoint = parseInt(e.keyIdentifier.substr(2), 16); + const char = String.fromCharCode(codepoint).toUpperCase(); + + return 'Platform' + char.charCodeAt(); + } + + return 'Unidentified'; + } + + _handleKeyDown(e) { + const code = this._getKeyCode(e); + let keysym = KeyboardUtil.getKeysym(e); + let numlock = e.getModifierState('NumLock'); + let capslock = e.getModifierState('CapsLock'); + + // getModifierState for NumLock is not supported on mac and ios and always returns false. + // Set to null to indicate unknown/unsupported instead. + if (browser.isMac() || browser.isIOS()) { + numlock = null; + } + + // Windows doesn't have a proper AltGr, but handles it using + // fake Ctrl+Alt. However the remote end might not be Windows, + // so we need to merge those in to a single AltGr event. We + // detect this case by seeing the two key events directly after + // each other with a very short time between them (<50ms). + if (this._altGrArmed) { + this._altGrArmed = false; + clearTimeout(this._altGrTimeout); + + if ((code === "AltRight") && + ((e.timeStamp - this._altGrCtrlTime) < 50)) { + // FIXME: We fail to detect this if either Ctrl key is + // first manually pressed as Windows then no + // longer sends the fake Ctrl down event. It + // does however happily send real Ctrl events + // even when AltGr is already down. Some + // browsers detect this for us though and set the + // key to "AltGraph". + keysym = KeyTable.XK_ISO_Level3_Shift; + } else { + this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true, numlock, capslock); + } + } + + // We cannot handle keys we cannot track, but we also need + // to deal with virtual keyboards which omit key info + if (code === 'Unidentified') { + if (keysym) { + // If it's a virtual keyboard then it should be + // sufficient to just send press and release right + // after each other + this._sendKeyEvent(keysym, code, true, numlock, capslock); + this._sendKeyEvent(keysym, code, false, numlock, capslock); + } + + stopEvent(e); + return; + } + + // Alt behaves more like AltGraph on macOS, so shuffle the + // keys around a bit to make things more sane for the remote + // server. This method is used by RealVNC and TigerVNC (and + // possibly others). + if (browser.isMac() || browser.isIOS()) { + switch (keysym) { + case KeyTable.XK_Super_L: + keysym = KeyTable.XK_Alt_L; + break; + case KeyTable.XK_Super_R: + keysym = KeyTable.XK_Super_L; + break; + case KeyTable.XK_Alt_L: + keysym = KeyTable.XK_Mode_switch; + break; + case KeyTable.XK_Alt_R: + keysym = KeyTable.XK_ISO_Level3_Shift; + break; + } + } + + // Is this key already pressed? If so, then we must use the + // same keysym or we'll confuse the server + if (code in this._keyDownList) { + keysym = this._keyDownList[code]; + } + + // macOS doesn't send proper key releases if a key is pressed + // while meta is held down + if ((browser.isMac() || browser.isIOS()) && + (e.metaKey && code !== 'MetaLeft' && code !== 'MetaRight')) { + this._sendKeyEvent(keysym, code, true, numlock, capslock); + this._sendKeyEvent(keysym, code, false, numlock, capslock); + stopEvent(e); + return; + } + + // macOS doesn't send proper key events for modifiers, only + // state change events. That gets extra confusing for CapsLock + // which toggles on each press, but not on release. So pretend + // it was a quick press and release of the button. + if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) { + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true, numlock, capslock); + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false, numlock, capslock); + stopEvent(e); + return; + } + + // Windows doesn't send proper key releases for a bunch of + // Japanese IM keys so we have to fake the release right away + const jpBadKeys = [ KeyTable.XK_Zenkaku_Hankaku, + KeyTable.XK_Eisu_toggle, + KeyTable.XK_Katakana, + KeyTable.XK_Hiragana, + KeyTable.XK_Romaji ]; + if (browser.isWindows() && jpBadKeys.includes(keysym)) { + this._sendKeyEvent(keysym, code, true, numlock, capslock); + this._sendKeyEvent(keysym, code, false, numlock, capslock); + stopEvent(e); + return; + } + + stopEvent(e); + + // Possible start of AltGr sequence? (see above) + if ((code === "ControlLeft") && browser.isWindows() && + !("ControlLeft" in this._keyDownList)) { + this._altGrArmed = true; + this._altGrTimeout = setTimeout(this._interruptAltGrSequence.bind(this), 100); + this._altGrCtrlTime = e.timeStamp; + return; + } + + this._sendKeyEvent(keysym, code, true, numlock, capslock); + } + + _handleKeyUp(e) { + stopEvent(e); + + const code = this._getKeyCode(e); + + // We can't get a release in the middle of an AltGr sequence, so + // abort that detection + this._interruptAltGrSequence(); + + // See comment in _handleKeyDown() + if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) { + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true); + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false); + return; + } + + this._sendKeyEvent(this._keyDownList[code], code, false); + + // Windows has a rather nasty bug where it won't send key + // release events for a Shift button if the other Shift is still + // pressed + if (browser.isWindows() && ((code === 'ShiftLeft') || + (code === 'ShiftRight'))) { + if ('ShiftRight' in this._keyDownList) { + this._sendKeyEvent(this._keyDownList['ShiftRight'], + 'ShiftRight', false); + } + if ('ShiftLeft' in this._keyDownList) { + this._sendKeyEvent(this._keyDownList['ShiftLeft'], + 'ShiftLeft', false); + } + } + } + + _interruptAltGrSequence() { + if (this._altGrArmed) { + this._altGrArmed = false; + clearTimeout(this._altGrTimeout); + this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); + } + } + + _allKeysUp() { + Log.Debug(">> Keyboard.allKeysUp"); + + // Prevent control key being processed after losing focus. + this._interruptAltGrSequence(); + + for (let code in this._keyDownList) { + this._sendKeyEvent(this._keyDownList[code], code, false); + } + Log.Debug("<< Keyboard.allKeysUp"); + } + + // ===== PUBLIC METHODS ===== + + grab() { + //Log.Debug(">> Keyboard.grab"); + + this._target.addEventListener('keydown', this._eventHandlers.keydown); + this._target.addEventListener('keyup', this._eventHandlers.keyup); + + // Release (key up) if window loses focus + window.addEventListener('blur', this._eventHandlers.blur); + + //Log.Debug("<< Keyboard.grab"); + } + + ungrab() { + //Log.Debug(">> Keyboard.ungrab"); + + this._target.removeEventListener('keydown', this._eventHandlers.keydown); + this._target.removeEventListener('keyup', this._eventHandlers.keyup); + window.removeEventListener('blur', this._eventHandlers.blur); + + // Release (key up) all keys that are in a down state + this._allKeysUp(); + + //Log.Debug(">> Keyboard.ungrab"); + } +} diff --git a/engine/static/vendor/novnc/core/input/keysym.js b/engine/static/vendor/novnc/core/input/keysym.js new file mode 100644 index 00000000..22ba0584 --- /dev/null +++ b/engine/static/vendor/novnc/core/input/keysym.js @@ -0,0 +1,616 @@ +/* eslint-disable key-spacing */ + +export default { + XK_VoidSymbol: 0xffffff, /* Void symbol */ + + XK_BackSpace: 0xff08, /* Back space, back char */ + XK_Tab: 0xff09, + XK_Linefeed: 0xff0a, /* Linefeed, LF */ + XK_Clear: 0xff0b, + XK_Return: 0xff0d, /* Return, enter */ + XK_Pause: 0xff13, /* Pause, hold */ + XK_Scroll_Lock: 0xff14, + XK_Sys_Req: 0xff15, + XK_Escape: 0xff1b, + XK_Delete: 0xffff, /* Delete, rubout */ + + /* International & multi-key character composition */ + + XK_Multi_key: 0xff20, /* Multi-key character compose */ + XK_Codeinput: 0xff37, + XK_SingleCandidate: 0xff3c, + XK_MultipleCandidate: 0xff3d, + XK_PreviousCandidate: 0xff3e, + + /* Japanese keyboard support */ + + XK_Kanji: 0xff21, /* Kanji, Kanji convert */ + XK_Muhenkan: 0xff22, /* Cancel Conversion */ + XK_Henkan_Mode: 0xff23, /* Start/Stop Conversion */ + XK_Henkan: 0xff23, /* Alias for Henkan_Mode */ + XK_Romaji: 0xff24, /* to Romaji */ + XK_Hiragana: 0xff25, /* to Hiragana */ + XK_Katakana: 0xff26, /* to Katakana */ + XK_Hiragana_Katakana: 0xff27, /* Hiragana/Katakana toggle */ + XK_Zenkaku: 0xff28, /* to Zenkaku */ + XK_Hankaku: 0xff29, /* to Hankaku */ + XK_Zenkaku_Hankaku: 0xff2a, /* Zenkaku/Hankaku toggle */ + XK_Touroku: 0xff2b, /* Add to Dictionary */ + XK_Massyo: 0xff2c, /* Delete from Dictionary */ + XK_Kana_Lock: 0xff2d, /* Kana Lock */ + XK_Kana_Shift: 0xff2e, /* Kana Shift */ + XK_Eisu_Shift: 0xff2f, /* Alphanumeric Shift */ + XK_Eisu_toggle: 0xff30, /* Alphanumeric toggle */ + XK_Kanji_Bangou: 0xff37, /* Codeinput */ + XK_Zen_Koho: 0xff3d, /* Multiple/All Candidate(s) */ + XK_Mae_Koho: 0xff3e, /* Previous Candidate */ + + /* Cursor control & motion */ + + XK_Home: 0xff50, + XK_Left: 0xff51, /* Move left, left arrow */ + XK_Up: 0xff52, /* Move up, up arrow */ + XK_Right: 0xff53, /* Move right, right arrow */ + XK_Down: 0xff54, /* Move down, down arrow */ + XK_Prior: 0xff55, /* Prior, previous */ + XK_Page_Up: 0xff55, + XK_Next: 0xff56, /* Next */ + XK_Page_Down: 0xff56, + XK_End: 0xff57, /* EOL */ + XK_Begin: 0xff58, /* BOL */ + + + /* Misc functions */ + + XK_Select: 0xff60, /* Select, mark */ + XK_Print: 0xff61, + XK_Execute: 0xff62, /* Execute, run, do */ + XK_Insert: 0xff63, /* Insert, insert here */ + XK_Undo: 0xff65, + XK_Redo: 0xff66, /* Redo, again */ + XK_Menu: 0xff67, + XK_Find: 0xff68, /* Find, search */ + XK_Cancel: 0xff69, /* Cancel, stop, abort, exit */ + XK_Help: 0xff6a, /* Help */ + XK_Break: 0xff6b, + XK_Mode_switch: 0xff7e, /* Character set switch */ + XK_script_switch: 0xff7e, /* Alias for mode_switch */ + XK_Num_Lock: 0xff7f, + + /* Keypad functions, keypad numbers cleverly chosen to map to ASCII */ + + XK_KP_Space: 0xff80, /* Space */ + XK_KP_Tab: 0xff89, + XK_KP_Enter: 0xff8d, /* Enter */ + XK_KP_F1: 0xff91, /* PF1, KP_A, ... */ + XK_KP_F2: 0xff92, + XK_KP_F3: 0xff93, + XK_KP_F4: 0xff94, + XK_KP_Home: 0xff95, + XK_KP_Left: 0xff96, + XK_KP_Up: 0xff97, + XK_KP_Right: 0xff98, + XK_KP_Down: 0xff99, + XK_KP_Prior: 0xff9a, + XK_KP_Page_Up: 0xff9a, + XK_KP_Next: 0xff9b, + XK_KP_Page_Down: 0xff9b, + XK_KP_End: 0xff9c, + XK_KP_Begin: 0xff9d, + XK_KP_Insert: 0xff9e, + XK_KP_Delete: 0xff9f, + XK_KP_Equal: 0xffbd, /* Equals */ + XK_KP_Multiply: 0xffaa, + XK_KP_Add: 0xffab, + XK_KP_Separator: 0xffac, /* Separator, often comma */ + XK_KP_Subtract: 0xffad, + XK_KP_Decimal: 0xffae, + XK_KP_Divide: 0xffaf, + + XK_KP_0: 0xffb0, + XK_KP_1: 0xffb1, + XK_KP_2: 0xffb2, + XK_KP_3: 0xffb3, + XK_KP_4: 0xffb4, + XK_KP_5: 0xffb5, + XK_KP_6: 0xffb6, + XK_KP_7: 0xffb7, + XK_KP_8: 0xffb8, + XK_KP_9: 0xffb9, + + /* + * Auxiliary functions; note the duplicate definitions for left and right + * function keys; Sun keyboards and a few other manufacturers have such + * function key groups on the left and/or right sides of the keyboard. + * We've not found a keyboard with more than 35 function keys total. + */ + + XK_F1: 0xffbe, + XK_F2: 0xffbf, + XK_F3: 0xffc0, + XK_F4: 0xffc1, + XK_F5: 0xffc2, + XK_F6: 0xffc3, + XK_F7: 0xffc4, + XK_F8: 0xffc5, + XK_F9: 0xffc6, + XK_F10: 0xffc7, + XK_F11: 0xffc8, + XK_L1: 0xffc8, + XK_F12: 0xffc9, + XK_L2: 0xffc9, + XK_F13: 0xffca, + XK_L3: 0xffca, + XK_F14: 0xffcb, + XK_L4: 0xffcb, + XK_F15: 0xffcc, + XK_L5: 0xffcc, + XK_F16: 0xffcd, + XK_L6: 0xffcd, + XK_F17: 0xffce, + XK_L7: 0xffce, + XK_F18: 0xffcf, + XK_L8: 0xffcf, + XK_F19: 0xffd0, + XK_L9: 0xffd0, + XK_F20: 0xffd1, + XK_L10: 0xffd1, + XK_F21: 0xffd2, + XK_R1: 0xffd2, + XK_F22: 0xffd3, + XK_R2: 0xffd3, + XK_F23: 0xffd4, + XK_R3: 0xffd4, + XK_F24: 0xffd5, + XK_R4: 0xffd5, + XK_F25: 0xffd6, + XK_R5: 0xffd6, + XK_F26: 0xffd7, + XK_R6: 0xffd7, + XK_F27: 0xffd8, + XK_R7: 0xffd8, + XK_F28: 0xffd9, + XK_R8: 0xffd9, + XK_F29: 0xffda, + XK_R9: 0xffda, + XK_F30: 0xffdb, + XK_R10: 0xffdb, + XK_F31: 0xffdc, + XK_R11: 0xffdc, + XK_F32: 0xffdd, + XK_R12: 0xffdd, + XK_F33: 0xffde, + XK_R13: 0xffde, + XK_F34: 0xffdf, + XK_R14: 0xffdf, + XK_F35: 0xffe0, + XK_R15: 0xffe0, + + /* Modifiers */ + + XK_Shift_L: 0xffe1, /* Left shift */ + XK_Shift_R: 0xffe2, /* Right shift */ + XK_Control_L: 0xffe3, /* Left control */ + XK_Control_R: 0xffe4, /* Right control */ + XK_Caps_Lock: 0xffe5, /* Caps lock */ + XK_Shift_Lock: 0xffe6, /* Shift lock */ + + XK_Meta_L: 0xffe7, /* Left meta */ + XK_Meta_R: 0xffe8, /* Right meta */ + XK_Alt_L: 0xffe9, /* Left alt */ + XK_Alt_R: 0xffea, /* Right alt */ + XK_Super_L: 0xffeb, /* Left super */ + XK_Super_R: 0xffec, /* Right super */ + XK_Hyper_L: 0xffed, /* Left hyper */ + XK_Hyper_R: 0xffee, /* Right hyper */ + + /* + * Keyboard (XKB) Extension function and modifier keys + * (from Appendix C of "The X Keyboard Extension: Protocol Specification") + * Byte 3 = 0xfe + */ + + XK_ISO_Level3_Shift: 0xfe03, /* AltGr */ + XK_ISO_Next_Group: 0xfe08, + XK_ISO_Prev_Group: 0xfe0a, + XK_ISO_First_Group: 0xfe0c, + XK_ISO_Last_Group: 0xfe0e, + + /* + * Latin 1 + * (ISO/IEC 8859-1: Unicode U+0020..U+00FF) + * Byte 3: 0 + */ + + XK_space: 0x0020, /* U+0020 SPACE */ + XK_exclam: 0x0021, /* U+0021 EXCLAMATION MARK */ + XK_quotedbl: 0x0022, /* U+0022 QUOTATION MARK */ + XK_numbersign: 0x0023, /* U+0023 NUMBER SIGN */ + XK_dollar: 0x0024, /* U+0024 DOLLAR SIGN */ + XK_percent: 0x0025, /* U+0025 PERCENT SIGN */ + XK_ampersand: 0x0026, /* U+0026 AMPERSAND */ + XK_apostrophe: 0x0027, /* U+0027 APOSTROPHE */ + XK_quoteright: 0x0027, /* deprecated */ + XK_parenleft: 0x0028, /* U+0028 LEFT PARENTHESIS */ + XK_parenright: 0x0029, /* U+0029 RIGHT PARENTHESIS */ + XK_asterisk: 0x002a, /* U+002A ASTERISK */ + XK_plus: 0x002b, /* U+002B PLUS SIGN */ + XK_comma: 0x002c, /* U+002C COMMA */ + XK_minus: 0x002d, /* U+002D HYPHEN-MINUS */ + XK_period: 0x002e, /* U+002E FULL STOP */ + XK_slash: 0x002f, /* U+002F SOLIDUS */ + XK_0: 0x0030, /* U+0030 DIGIT ZERO */ + XK_1: 0x0031, /* U+0031 DIGIT ONE */ + XK_2: 0x0032, /* U+0032 DIGIT TWO */ + XK_3: 0x0033, /* U+0033 DIGIT THREE */ + XK_4: 0x0034, /* U+0034 DIGIT FOUR */ + XK_5: 0x0035, /* U+0035 DIGIT FIVE */ + XK_6: 0x0036, /* U+0036 DIGIT SIX */ + XK_7: 0x0037, /* U+0037 DIGIT SEVEN */ + XK_8: 0x0038, /* U+0038 DIGIT EIGHT */ + XK_9: 0x0039, /* U+0039 DIGIT NINE */ + XK_colon: 0x003a, /* U+003A COLON */ + XK_semicolon: 0x003b, /* U+003B SEMICOLON */ + XK_less: 0x003c, /* U+003C LESS-THAN SIGN */ + XK_equal: 0x003d, /* U+003D EQUALS SIGN */ + XK_greater: 0x003e, /* U+003E GREATER-THAN SIGN */ + XK_question: 0x003f, /* U+003F QUESTION MARK */ + XK_at: 0x0040, /* U+0040 COMMERCIAL AT */ + XK_A: 0x0041, /* U+0041 LATIN CAPITAL LETTER A */ + XK_B: 0x0042, /* U+0042 LATIN CAPITAL LETTER B */ + XK_C: 0x0043, /* U+0043 LATIN CAPITAL LETTER C */ + XK_D: 0x0044, /* U+0044 LATIN CAPITAL LETTER D */ + XK_E: 0x0045, /* U+0045 LATIN CAPITAL LETTER E */ + XK_F: 0x0046, /* U+0046 LATIN CAPITAL LETTER F */ + XK_G: 0x0047, /* U+0047 LATIN CAPITAL LETTER G */ + XK_H: 0x0048, /* U+0048 LATIN CAPITAL LETTER H */ + XK_I: 0x0049, /* U+0049 LATIN CAPITAL LETTER I */ + XK_J: 0x004a, /* U+004A LATIN CAPITAL LETTER J */ + XK_K: 0x004b, /* U+004B LATIN CAPITAL LETTER K */ + XK_L: 0x004c, /* U+004C LATIN CAPITAL LETTER L */ + XK_M: 0x004d, /* U+004D LATIN CAPITAL LETTER M */ + XK_N: 0x004e, /* U+004E LATIN CAPITAL LETTER N */ + XK_O: 0x004f, /* U+004F LATIN CAPITAL LETTER O */ + XK_P: 0x0050, /* U+0050 LATIN CAPITAL LETTER P */ + XK_Q: 0x0051, /* U+0051 LATIN CAPITAL LETTER Q */ + XK_R: 0x0052, /* U+0052 LATIN CAPITAL LETTER R */ + XK_S: 0x0053, /* U+0053 LATIN CAPITAL LETTER S */ + XK_T: 0x0054, /* U+0054 LATIN CAPITAL LETTER T */ + XK_U: 0x0055, /* U+0055 LATIN CAPITAL LETTER U */ + XK_V: 0x0056, /* U+0056 LATIN CAPITAL LETTER V */ + XK_W: 0x0057, /* U+0057 LATIN CAPITAL LETTER W */ + XK_X: 0x0058, /* U+0058 LATIN CAPITAL LETTER X */ + XK_Y: 0x0059, /* U+0059 LATIN CAPITAL LETTER Y */ + XK_Z: 0x005a, /* U+005A LATIN CAPITAL LETTER Z */ + XK_bracketleft: 0x005b, /* U+005B LEFT SQUARE BRACKET */ + XK_backslash: 0x005c, /* U+005C REVERSE SOLIDUS */ + XK_bracketright: 0x005d, /* U+005D RIGHT SQUARE BRACKET */ + XK_asciicircum: 0x005e, /* U+005E CIRCUMFLEX ACCENT */ + XK_underscore: 0x005f, /* U+005F LOW LINE */ + XK_grave: 0x0060, /* U+0060 GRAVE ACCENT */ + XK_quoteleft: 0x0060, /* deprecated */ + XK_a: 0x0061, /* U+0061 LATIN SMALL LETTER A */ + XK_b: 0x0062, /* U+0062 LATIN SMALL LETTER B */ + XK_c: 0x0063, /* U+0063 LATIN SMALL LETTER C */ + XK_d: 0x0064, /* U+0064 LATIN SMALL LETTER D */ + XK_e: 0x0065, /* U+0065 LATIN SMALL LETTER E */ + XK_f: 0x0066, /* U+0066 LATIN SMALL LETTER F */ + XK_g: 0x0067, /* U+0067 LATIN SMALL LETTER G */ + XK_h: 0x0068, /* U+0068 LATIN SMALL LETTER H */ + XK_i: 0x0069, /* U+0069 LATIN SMALL LETTER I */ + XK_j: 0x006a, /* U+006A LATIN SMALL LETTER J */ + XK_k: 0x006b, /* U+006B LATIN SMALL LETTER K */ + XK_l: 0x006c, /* U+006C LATIN SMALL LETTER L */ + XK_m: 0x006d, /* U+006D LATIN SMALL LETTER M */ + XK_n: 0x006e, /* U+006E LATIN SMALL LETTER N */ + XK_o: 0x006f, /* U+006F LATIN SMALL LETTER O */ + XK_p: 0x0070, /* U+0070 LATIN SMALL LETTER P */ + XK_q: 0x0071, /* U+0071 LATIN SMALL LETTER Q */ + XK_r: 0x0072, /* U+0072 LATIN SMALL LETTER R */ + XK_s: 0x0073, /* U+0073 LATIN SMALL LETTER S */ + XK_t: 0x0074, /* U+0074 LATIN SMALL LETTER T */ + XK_u: 0x0075, /* U+0075 LATIN SMALL LETTER U */ + XK_v: 0x0076, /* U+0076 LATIN SMALL LETTER V */ + XK_w: 0x0077, /* U+0077 LATIN SMALL LETTER W */ + XK_x: 0x0078, /* U+0078 LATIN SMALL LETTER X */ + XK_y: 0x0079, /* U+0079 LATIN SMALL LETTER Y */ + XK_z: 0x007a, /* U+007A LATIN SMALL LETTER Z */ + XK_braceleft: 0x007b, /* U+007B LEFT CURLY BRACKET */ + XK_bar: 0x007c, /* U+007C VERTICAL LINE */ + XK_braceright: 0x007d, /* U+007D RIGHT CURLY BRACKET */ + XK_asciitilde: 0x007e, /* U+007E TILDE */ + + XK_nobreakspace: 0x00a0, /* U+00A0 NO-BREAK SPACE */ + XK_exclamdown: 0x00a1, /* U+00A1 INVERTED EXCLAMATION MARK */ + XK_cent: 0x00a2, /* U+00A2 CENT SIGN */ + XK_sterling: 0x00a3, /* U+00A3 POUND SIGN */ + XK_currency: 0x00a4, /* U+00A4 CURRENCY SIGN */ + XK_yen: 0x00a5, /* U+00A5 YEN SIGN */ + XK_brokenbar: 0x00a6, /* U+00A6 BROKEN BAR */ + XK_section: 0x00a7, /* U+00A7 SECTION SIGN */ + XK_diaeresis: 0x00a8, /* U+00A8 DIAERESIS */ + XK_copyright: 0x00a9, /* U+00A9 COPYRIGHT SIGN */ + XK_ordfeminine: 0x00aa, /* U+00AA FEMININE ORDINAL INDICATOR */ + XK_guillemotleft: 0x00ab, /* U+00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */ + XK_notsign: 0x00ac, /* U+00AC NOT SIGN */ + XK_hyphen: 0x00ad, /* U+00AD SOFT HYPHEN */ + XK_registered: 0x00ae, /* U+00AE REGISTERED SIGN */ + XK_macron: 0x00af, /* U+00AF MACRON */ + XK_degree: 0x00b0, /* U+00B0 DEGREE SIGN */ + XK_plusminus: 0x00b1, /* U+00B1 PLUS-MINUS SIGN */ + XK_twosuperior: 0x00b2, /* U+00B2 SUPERSCRIPT TWO */ + XK_threesuperior: 0x00b3, /* U+00B3 SUPERSCRIPT THREE */ + XK_acute: 0x00b4, /* U+00B4 ACUTE ACCENT */ + XK_mu: 0x00b5, /* U+00B5 MICRO SIGN */ + XK_paragraph: 0x00b6, /* U+00B6 PILCROW SIGN */ + XK_periodcentered: 0x00b7, /* U+00B7 MIDDLE DOT */ + XK_cedilla: 0x00b8, /* U+00B8 CEDILLA */ + XK_onesuperior: 0x00b9, /* U+00B9 SUPERSCRIPT ONE */ + XK_masculine: 0x00ba, /* U+00BA MASCULINE ORDINAL INDICATOR */ + XK_guillemotright: 0x00bb, /* U+00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */ + XK_onequarter: 0x00bc, /* U+00BC VULGAR FRACTION ONE QUARTER */ + XK_onehalf: 0x00bd, /* U+00BD VULGAR FRACTION ONE HALF */ + XK_threequarters: 0x00be, /* U+00BE VULGAR FRACTION THREE QUARTERS */ + XK_questiondown: 0x00bf, /* U+00BF INVERTED QUESTION MARK */ + XK_Agrave: 0x00c0, /* U+00C0 LATIN CAPITAL LETTER A WITH GRAVE */ + XK_Aacute: 0x00c1, /* U+00C1 LATIN CAPITAL LETTER A WITH ACUTE */ + XK_Acircumflex: 0x00c2, /* U+00C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */ + XK_Atilde: 0x00c3, /* U+00C3 LATIN CAPITAL LETTER A WITH TILDE */ + XK_Adiaeresis: 0x00c4, /* U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS */ + XK_Aring: 0x00c5, /* U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE */ + XK_AE: 0x00c6, /* U+00C6 LATIN CAPITAL LETTER AE */ + XK_Ccedilla: 0x00c7, /* U+00C7 LATIN CAPITAL LETTER C WITH CEDILLA */ + XK_Egrave: 0x00c8, /* U+00C8 LATIN CAPITAL LETTER E WITH GRAVE */ + XK_Eacute: 0x00c9, /* U+00C9 LATIN CAPITAL LETTER E WITH ACUTE */ + XK_Ecircumflex: 0x00ca, /* U+00CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX */ + XK_Ediaeresis: 0x00cb, /* U+00CB LATIN CAPITAL LETTER E WITH DIAERESIS */ + XK_Igrave: 0x00cc, /* U+00CC LATIN CAPITAL LETTER I WITH GRAVE */ + XK_Iacute: 0x00cd, /* U+00CD LATIN CAPITAL LETTER I WITH ACUTE */ + XK_Icircumflex: 0x00ce, /* U+00CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX */ + XK_Idiaeresis: 0x00cf, /* U+00CF LATIN CAPITAL LETTER I WITH DIAERESIS */ + XK_ETH: 0x00d0, /* U+00D0 LATIN CAPITAL LETTER ETH */ + XK_Eth: 0x00d0, /* deprecated */ + XK_Ntilde: 0x00d1, /* U+00D1 LATIN CAPITAL LETTER N WITH TILDE */ + XK_Ograve: 0x00d2, /* U+00D2 LATIN CAPITAL LETTER O WITH GRAVE */ + XK_Oacute: 0x00d3, /* U+00D3 LATIN CAPITAL LETTER O WITH ACUTE */ + XK_Ocircumflex: 0x00d4, /* U+00D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX */ + XK_Otilde: 0x00d5, /* U+00D5 LATIN CAPITAL LETTER O WITH TILDE */ + XK_Odiaeresis: 0x00d6, /* U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS */ + XK_multiply: 0x00d7, /* U+00D7 MULTIPLICATION SIGN */ + XK_Oslash: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ + XK_Ooblique: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ + XK_Ugrave: 0x00d9, /* U+00D9 LATIN CAPITAL LETTER U WITH GRAVE */ + XK_Uacute: 0x00da, /* U+00DA LATIN CAPITAL LETTER U WITH ACUTE */ + XK_Ucircumflex: 0x00db, /* U+00DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX */ + XK_Udiaeresis: 0x00dc, /* U+00DC LATIN CAPITAL LETTER U WITH DIAERESIS */ + XK_Yacute: 0x00dd, /* U+00DD LATIN CAPITAL LETTER Y WITH ACUTE */ + XK_THORN: 0x00de, /* U+00DE LATIN CAPITAL LETTER THORN */ + XK_Thorn: 0x00de, /* deprecated */ + XK_ssharp: 0x00df, /* U+00DF LATIN SMALL LETTER SHARP S */ + XK_agrave: 0x00e0, /* U+00E0 LATIN SMALL LETTER A WITH GRAVE */ + XK_aacute: 0x00e1, /* U+00E1 LATIN SMALL LETTER A WITH ACUTE */ + XK_acircumflex: 0x00e2, /* U+00E2 LATIN SMALL LETTER A WITH CIRCUMFLEX */ + XK_atilde: 0x00e3, /* U+00E3 LATIN SMALL LETTER A WITH TILDE */ + XK_adiaeresis: 0x00e4, /* U+00E4 LATIN SMALL LETTER A WITH DIAERESIS */ + XK_aring: 0x00e5, /* U+00E5 LATIN SMALL LETTER A WITH RING ABOVE */ + XK_ae: 0x00e6, /* U+00E6 LATIN SMALL LETTER AE */ + XK_ccedilla: 0x00e7, /* U+00E7 LATIN SMALL LETTER C WITH CEDILLA */ + XK_egrave: 0x00e8, /* U+00E8 LATIN SMALL LETTER E WITH GRAVE */ + XK_eacute: 0x00e9, /* U+00E9 LATIN SMALL LETTER E WITH ACUTE */ + XK_ecircumflex: 0x00ea, /* U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX */ + XK_ediaeresis: 0x00eb, /* U+00EB LATIN SMALL LETTER E WITH DIAERESIS */ + XK_igrave: 0x00ec, /* U+00EC LATIN SMALL LETTER I WITH GRAVE */ + XK_iacute: 0x00ed, /* U+00ED LATIN SMALL LETTER I WITH ACUTE */ + XK_icircumflex: 0x00ee, /* U+00EE LATIN SMALL LETTER I WITH CIRCUMFLEX */ + XK_idiaeresis: 0x00ef, /* U+00EF LATIN SMALL LETTER I WITH DIAERESIS */ + XK_eth: 0x00f0, /* U+00F0 LATIN SMALL LETTER ETH */ + XK_ntilde: 0x00f1, /* U+00F1 LATIN SMALL LETTER N WITH TILDE */ + XK_ograve: 0x00f2, /* U+00F2 LATIN SMALL LETTER O WITH GRAVE */ + XK_oacute: 0x00f3, /* U+00F3 LATIN SMALL LETTER O WITH ACUTE */ + XK_ocircumflex: 0x00f4, /* U+00F4 LATIN SMALL LETTER O WITH CIRCUMFLEX */ + XK_otilde: 0x00f5, /* U+00F5 LATIN SMALL LETTER O WITH TILDE */ + XK_odiaeresis: 0x00f6, /* U+00F6 LATIN SMALL LETTER O WITH DIAERESIS */ + XK_division: 0x00f7, /* U+00F7 DIVISION SIGN */ + XK_oslash: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ + XK_ooblique: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ + XK_ugrave: 0x00f9, /* U+00F9 LATIN SMALL LETTER U WITH GRAVE */ + XK_uacute: 0x00fa, /* U+00FA LATIN SMALL LETTER U WITH ACUTE */ + XK_ucircumflex: 0x00fb, /* U+00FB LATIN SMALL LETTER U WITH CIRCUMFLEX */ + XK_udiaeresis: 0x00fc, /* U+00FC LATIN SMALL LETTER U WITH DIAERESIS */ + XK_yacute: 0x00fd, /* U+00FD LATIN SMALL LETTER Y WITH ACUTE */ + XK_thorn: 0x00fe, /* U+00FE LATIN SMALL LETTER THORN */ + XK_ydiaeresis: 0x00ff, /* U+00FF LATIN SMALL LETTER Y WITH DIAERESIS */ + + /* + * Korean + * Byte 3 = 0x0e + */ + + XK_Hangul: 0xff31, /* Hangul start/stop(toggle) */ + XK_Hangul_Hanja: 0xff34, /* Start Hangul->Hanja Conversion */ + XK_Hangul_Jeonja: 0xff38, /* Jeonja mode */ + + /* + * XFree86 vendor specific keysyms. + * + * The XFree86 keysym range is 0x10080001 - 0x1008FFFF. + */ + + XF86XK_ModeLock: 0x1008FF01, + XF86XK_MonBrightnessUp: 0x1008FF02, + XF86XK_MonBrightnessDown: 0x1008FF03, + XF86XK_KbdLightOnOff: 0x1008FF04, + XF86XK_KbdBrightnessUp: 0x1008FF05, + XF86XK_KbdBrightnessDown: 0x1008FF06, + XF86XK_Standby: 0x1008FF10, + XF86XK_AudioLowerVolume: 0x1008FF11, + XF86XK_AudioMute: 0x1008FF12, + XF86XK_AudioRaiseVolume: 0x1008FF13, + XF86XK_AudioPlay: 0x1008FF14, + XF86XK_AudioStop: 0x1008FF15, + XF86XK_AudioPrev: 0x1008FF16, + XF86XK_AudioNext: 0x1008FF17, + XF86XK_HomePage: 0x1008FF18, + XF86XK_Mail: 0x1008FF19, + XF86XK_Start: 0x1008FF1A, + XF86XK_Search: 0x1008FF1B, + XF86XK_AudioRecord: 0x1008FF1C, + XF86XK_Calculator: 0x1008FF1D, + XF86XK_Memo: 0x1008FF1E, + XF86XK_ToDoList: 0x1008FF1F, + XF86XK_Calendar: 0x1008FF20, + XF86XK_PowerDown: 0x1008FF21, + XF86XK_ContrastAdjust: 0x1008FF22, + XF86XK_RockerUp: 0x1008FF23, + XF86XK_RockerDown: 0x1008FF24, + XF86XK_RockerEnter: 0x1008FF25, + XF86XK_Back: 0x1008FF26, + XF86XK_Forward: 0x1008FF27, + XF86XK_Stop: 0x1008FF28, + XF86XK_Refresh: 0x1008FF29, + XF86XK_PowerOff: 0x1008FF2A, + XF86XK_WakeUp: 0x1008FF2B, + XF86XK_Eject: 0x1008FF2C, + XF86XK_ScreenSaver: 0x1008FF2D, + XF86XK_WWW: 0x1008FF2E, + XF86XK_Sleep: 0x1008FF2F, + XF86XK_Favorites: 0x1008FF30, + XF86XK_AudioPause: 0x1008FF31, + XF86XK_AudioMedia: 0x1008FF32, + XF86XK_MyComputer: 0x1008FF33, + XF86XK_VendorHome: 0x1008FF34, + XF86XK_LightBulb: 0x1008FF35, + XF86XK_Shop: 0x1008FF36, + XF86XK_History: 0x1008FF37, + XF86XK_OpenURL: 0x1008FF38, + XF86XK_AddFavorite: 0x1008FF39, + XF86XK_HotLinks: 0x1008FF3A, + XF86XK_BrightnessAdjust: 0x1008FF3B, + XF86XK_Finance: 0x1008FF3C, + XF86XK_Community: 0x1008FF3D, + XF86XK_AudioRewind: 0x1008FF3E, + XF86XK_BackForward: 0x1008FF3F, + XF86XK_Launch0: 0x1008FF40, + XF86XK_Launch1: 0x1008FF41, + XF86XK_Launch2: 0x1008FF42, + XF86XK_Launch3: 0x1008FF43, + XF86XK_Launch4: 0x1008FF44, + XF86XK_Launch5: 0x1008FF45, + XF86XK_Launch6: 0x1008FF46, + XF86XK_Launch7: 0x1008FF47, + XF86XK_Launch8: 0x1008FF48, + XF86XK_Launch9: 0x1008FF49, + XF86XK_LaunchA: 0x1008FF4A, + XF86XK_LaunchB: 0x1008FF4B, + XF86XK_LaunchC: 0x1008FF4C, + XF86XK_LaunchD: 0x1008FF4D, + XF86XK_LaunchE: 0x1008FF4E, + XF86XK_LaunchF: 0x1008FF4F, + XF86XK_ApplicationLeft: 0x1008FF50, + XF86XK_ApplicationRight: 0x1008FF51, + XF86XK_Book: 0x1008FF52, + XF86XK_CD: 0x1008FF53, + XF86XK_Calculater: 0x1008FF54, + XF86XK_Clear: 0x1008FF55, + XF86XK_Close: 0x1008FF56, + XF86XK_Copy: 0x1008FF57, + XF86XK_Cut: 0x1008FF58, + XF86XK_Display: 0x1008FF59, + XF86XK_DOS: 0x1008FF5A, + XF86XK_Documents: 0x1008FF5B, + XF86XK_Excel: 0x1008FF5C, + XF86XK_Explorer: 0x1008FF5D, + XF86XK_Game: 0x1008FF5E, + XF86XK_Go: 0x1008FF5F, + XF86XK_iTouch: 0x1008FF60, + XF86XK_LogOff: 0x1008FF61, + XF86XK_Market: 0x1008FF62, + XF86XK_Meeting: 0x1008FF63, + XF86XK_MenuKB: 0x1008FF65, + XF86XK_MenuPB: 0x1008FF66, + XF86XK_MySites: 0x1008FF67, + XF86XK_New: 0x1008FF68, + XF86XK_News: 0x1008FF69, + XF86XK_OfficeHome: 0x1008FF6A, + XF86XK_Open: 0x1008FF6B, + XF86XK_Option: 0x1008FF6C, + XF86XK_Paste: 0x1008FF6D, + XF86XK_Phone: 0x1008FF6E, + XF86XK_Q: 0x1008FF70, + XF86XK_Reply: 0x1008FF72, + XF86XK_Reload: 0x1008FF73, + XF86XK_RotateWindows: 0x1008FF74, + XF86XK_RotationPB: 0x1008FF75, + XF86XK_RotationKB: 0x1008FF76, + XF86XK_Save: 0x1008FF77, + XF86XK_ScrollUp: 0x1008FF78, + XF86XK_ScrollDown: 0x1008FF79, + XF86XK_ScrollClick: 0x1008FF7A, + XF86XK_Send: 0x1008FF7B, + XF86XK_Spell: 0x1008FF7C, + XF86XK_SplitScreen: 0x1008FF7D, + XF86XK_Support: 0x1008FF7E, + XF86XK_TaskPane: 0x1008FF7F, + XF86XK_Terminal: 0x1008FF80, + XF86XK_Tools: 0x1008FF81, + XF86XK_Travel: 0x1008FF82, + XF86XK_UserPB: 0x1008FF84, + XF86XK_User1KB: 0x1008FF85, + XF86XK_User2KB: 0x1008FF86, + XF86XK_Video: 0x1008FF87, + XF86XK_WheelButton: 0x1008FF88, + XF86XK_Word: 0x1008FF89, + XF86XK_Xfer: 0x1008FF8A, + XF86XK_ZoomIn: 0x1008FF8B, + XF86XK_ZoomOut: 0x1008FF8C, + XF86XK_Away: 0x1008FF8D, + XF86XK_Messenger: 0x1008FF8E, + XF86XK_WebCam: 0x1008FF8F, + XF86XK_MailForward: 0x1008FF90, + XF86XK_Pictures: 0x1008FF91, + XF86XK_Music: 0x1008FF92, + XF86XK_Battery: 0x1008FF93, + XF86XK_Bluetooth: 0x1008FF94, + XF86XK_WLAN: 0x1008FF95, + XF86XK_UWB: 0x1008FF96, + XF86XK_AudioForward: 0x1008FF97, + XF86XK_AudioRepeat: 0x1008FF98, + XF86XK_AudioRandomPlay: 0x1008FF99, + XF86XK_Subtitle: 0x1008FF9A, + XF86XK_AudioCycleTrack: 0x1008FF9B, + XF86XK_CycleAngle: 0x1008FF9C, + XF86XK_FrameBack: 0x1008FF9D, + XF86XK_FrameForward: 0x1008FF9E, + XF86XK_Time: 0x1008FF9F, + XF86XK_Select: 0x1008FFA0, + XF86XK_View: 0x1008FFA1, + XF86XK_TopMenu: 0x1008FFA2, + XF86XK_Red: 0x1008FFA3, + XF86XK_Green: 0x1008FFA4, + XF86XK_Yellow: 0x1008FFA5, + XF86XK_Blue: 0x1008FFA6, + XF86XK_Suspend: 0x1008FFA7, + XF86XK_Hibernate: 0x1008FFA8, + XF86XK_TouchpadToggle: 0x1008FFA9, + XF86XK_TouchpadOn: 0x1008FFB0, + XF86XK_TouchpadOff: 0x1008FFB1, + XF86XK_AudioMicMute: 0x1008FFB2, + XF86XK_Switch_VT_1: 0x1008FE01, + XF86XK_Switch_VT_2: 0x1008FE02, + XF86XK_Switch_VT_3: 0x1008FE03, + XF86XK_Switch_VT_4: 0x1008FE04, + XF86XK_Switch_VT_5: 0x1008FE05, + XF86XK_Switch_VT_6: 0x1008FE06, + XF86XK_Switch_VT_7: 0x1008FE07, + XF86XK_Switch_VT_8: 0x1008FE08, + XF86XK_Switch_VT_9: 0x1008FE09, + XF86XK_Switch_VT_10: 0x1008FE0A, + XF86XK_Switch_VT_11: 0x1008FE0B, + XF86XK_Switch_VT_12: 0x1008FE0C, + XF86XK_Ungrab: 0x1008FE20, + XF86XK_ClearGrab: 0x1008FE21, + XF86XK_Next_VMode: 0x1008FE22, + XF86XK_Prev_VMode: 0x1008FE23, + XF86XK_LogWindowTree: 0x1008FE24, + XF86XK_LogGrabInfo: 0x1008FE25, +}; diff --git a/engine/static/vendor/novnc/core/input/keysymdef.js b/engine/static/vendor/novnc/core/input/keysymdef.js new file mode 100644 index 00000000..951cacab --- /dev/null +++ b/engine/static/vendor/novnc/core/input/keysymdef.js @@ -0,0 +1,688 @@ +/* + * Mapping from Unicode codepoints to X11/RFB keysyms + * + * This file was automatically generated from keysymdef.h + * DO NOT EDIT! + */ + +/* Functions at the bottom */ + +const codepoints = { + 0x0100: 0x03c0, // XK_Amacron + 0x0101: 0x03e0, // XK_amacron + 0x0102: 0x01c3, // XK_Abreve + 0x0103: 0x01e3, // XK_abreve + 0x0104: 0x01a1, // XK_Aogonek + 0x0105: 0x01b1, // XK_aogonek + 0x0106: 0x01c6, // XK_Cacute + 0x0107: 0x01e6, // XK_cacute + 0x0108: 0x02c6, // XK_Ccircumflex + 0x0109: 0x02e6, // XK_ccircumflex + 0x010a: 0x02c5, // XK_Cabovedot + 0x010b: 0x02e5, // XK_cabovedot + 0x010c: 0x01c8, // XK_Ccaron + 0x010d: 0x01e8, // XK_ccaron + 0x010e: 0x01cf, // XK_Dcaron + 0x010f: 0x01ef, // XK_dcaron + 0x0110: 0x01d0, // XK_Dstroke + 0x0111: 0x01f0, // XK_dstroke + 0x0112: 0x03aa, // XK_Emacron + 0x0113: 0x03ba, // XK_emacron + 0x0116: 0x03cc, // XK_Eabovedot + 0x0117: 0x03ec, // XK_eabovedot + 0x0118: 0x01ca, // XK_Eogonek + 0x0119: 0x01ea, // XK_eogonek + 0x011a: 0x01cc, // XK_Ecaron + 0x011b: 0x01ec, // XK_ecaron + 0x011c: 0x02d8, // XK_Gcircumflex + 0x011d: 0x02f8, // XK_gcircumflex + 0x011e: 0x02ab, // XK_Gbreve + 0x011f: 0x02bb, // XK_gbreve + 0x0120: 0x02d5, // XK_Gabovedot + 0x0121: 0x02f5, // XK_gabovedot + 0x0122: 0x03ab, // XK_Gcedilla + 0x0123: 0x03bb, // XK_gcedilla + 0x0124: 0x02a6, // XK_Hcircumflex + 0x0125: 0x02b6, // XK_hcircumflex + 0x0126: 0x02a1, // XK_Hstroke + 0x0127: 0x02b1, // XK_hstroke + 0x0128: 0x03a5, // XK_Itilde + 0x0129: 0x03b5, // XK_itilde + 0x012a: 0x03cf, // XK_Imacron + 0x012b: 0x03ef, // XK_imacron + 0x012e: 0x03c7, // XK_Iogonek + 0x012f: 0x03e7, // XK_iogonek + 0x0130: 0x02a9, // XK_Iabovedot + 0x0131: 0x02b9, // XK_idotless + 0x0134: 0x02ac, // XK_Jcircumflex + 0x0135: 0x02bc, // XK_jcircumflex + 0x0136: 0x03d3, // XK_Kcedilla + 0x0137: 0x03f3, // XK_kcedilla + 0x0138: 0x03a2, // XK_kra + 0x0139: 0x01c5, // XK_Lacute + 0x013a: 0x01e5, // XK_lacute + 0x013b: 0x03a6, // XK_Lcedilla + 0x013c: 0x03b6, // XK_lcedilla + 0x013d: 0x01a5, // XK_Lcaron + 0x013e: 0x01b5, // XK_lcaron + 0x0141: 0x01a3, // XK_Lstroke + 0x0142: 0x01b3, // XK_lstroke + 0x0143: 0x01d1, // XK_Nacute + 0x0144: 0x01f1, // XK_nacute + 0x0145: 0x03d1, // XK_Ncedilla + 0x0146: 0x03f1, // XK_ncedilla + 0x0147: 0x01d2, // XK_Ncaron + 0x0148: 0x01f2, // XK_ncaron + 0x014a: 0x03bd, // XK_ENG + 0x014b: 0x03bf, // XK_eng + 0x014c: 0x03d2, // XK_Omacron + 0x014d: 0x03f2, // XK_omacron + 0x0150: 0x01d5, // XK_Odoubleacute + 0x0151: 0x01f5, // XK_odoubleacute + 0x0152: 0x13bc, // XK_OE + 0x0153: 0x13bd, // XK_oe + 0x0154: 0x01c0, // XK_Racute + 0x0155: 0x01e0, // XK_racute + 0x0156: 0x03a3, // XK_Rcedilla + 0x0157: 0x03b3, // XK_rcedilla + 0x0158: 0x01d8, // XK_Rcaron + 0x0159: 0x01f8, // XK_rcaron + 0x015a: 0x01a6, // XK_Sacute + 0x015b: 0x01b6, // XK_sacute + 0x015c: 0x02de, // XK_Scircumflex + 0x015d: 0x02fe, // XK_scircumflex + 0x015e: 0x01aa, // XK_Scedilla + 0x015f: 0x01ba, // XK_scedilla + 0x0160: 0x01a9, // XK_Scaron + 0x0161: 0x01b9, // XK_scaron + 0x0162: 0x01de, // XK_Tcedilla + 0x0163: 0x01fe, // XK_tcedilla + 0x0164: 0x01ab, // XK_Tcaron + 0x0165: 0x01bb, // XK_tcaron + 0x0166: 0x03ac, // XK_Tslash + 0x0167: 0x03bc, // XK_tslash + 0x0168: 0x03dd, // XK_Utilde + 0x0169: 0x03fd, // XK_utilde + 0x016a: 0x03de, // XK_Umacron + 0x016b: 0x03fe, // XK_umacron + 0x016c: 0x02dd, // XK_Ubreve + 0x016d: 0x02fd, // XK_ubreve + 0x016e: 0x01d9, // XK_Uring + 0x016f: 0x01f9, // XK_uring + 0x0170: 0x01db, // XK_Udoubleacute + 0x0171: 0x01fb, // XK_udoubleacute + 0x0172: 0x03d9, // XK_Uogonek + 0x0173: 0x03f9, // XK_uogonek + 0x0178: 0x13be, // XK_Ydiaeresis + 0x0179: 0x01ac, // XK_Zacute + 0x017a: 0x01bc, // XK_zacute + 0x017b: 0x01af, // XK_Zabovedot + 0x017c: 0x01bf, // XK_zabovedot + 0x017d: 0x01ae, // XK_Zcaron + 0x017e: 0x01be, // XK_zcaron + 0x0192: 0x08f6, // XK_function + 0x01d2: 0x10001d1, // XK_Ocaron + 0x02c7: 0x01b7, // XK_caron + 0x02d8: 0x01a2, // XK_breve + 0x02d9: 0x01ff, // XK_abovedot + 0x02db: 0x01b2, // XK_ogonek + 0x02dd: 0x01bd, // XK_doubleacute + 0x0385: 0x07ae, // XK_Greek_accentdieresis + 0x0386: 0x07a1, // XK_Greek_ALPHAaccent + 0x0388: 0x07a2, // XK_Greek_EPSILONaccent + 0x0389: 0x07a3, // XK_Greek_ETAaccent + 0x038a: 0x07a4, // XK_Greek_IOTAaccent + 0x038c: 0x07a7, // XK_Greek_OMICRONaccent + 0x038e: 0x07a8, // XK_Greek_UPSILONaccent + 0x038f: 0x07ab, // XK_Greek_OMEGAaccent + 0x0390: 0x07b6, // XK_Greek_iotaaccentdieresis + 0x0391: 0x07c1, // XK_Greek_ALPHA + 0x0392: 0x07c2, // XK_Greek_BETA + 0x0393: 0x07c3, // XK_Greek_GAMMA + 0x0394: 0x07c4, // XK_Greek_DELTA + 0x0395: 0x07c5, // XK_Greek_EPSILON + 0x0396: 0x07c6, // XK_Greek_ZETA + 0x0397: 0x07c7, // XK_Greek_ETA + 0x0398: 0x07c8, // XK_Greek_THETA + 0x0399: 0x07c9, // XK_Greek_IOTA + 0x039a: 0x07ca, // XK_Greek_KAPPA + 0x039b: 0x07cb, // XK_Greek_LAMDA + 0x039c: 0x07cc, // XK_Greek_MU + 0x039d: 0x07cd, // XK_Greek_NU + 0x039e: 0x07ce, // XK_Greek_XI + 0x039f: 0x07cf, // XK_Greek_OMICRON + 0x03a0: 0x07d0, // XK_Greek_PI + 0x03a1: 0x07d1, // XK_Greek_RHO + 0x03a3: 0x07d2, // XK_Greek_SIGMA + 0x03a4: 0x07d4, // XK_Greek_TAU + 0x03a5: 0x07d5, // XK_Greek_UPSILON + 0x03a6: 0x07d6, // XK_Greek_PHI + 0x03a7: 0x07d7, // XK_Greek_CHI + 0x03a8: 0x07d8, // XK_Greek_PSI + 0x03a9: 0x07d9, // XK_Greek_OMEGA + 0x03aa: 0x07a5, // XK_Greek_IOTAdieresis + 0x03ab: 0x07a9, // XK_Greek_UPSILONdieresis + 0x03ac: 0x07b1, // XK_Greek_alphaaccent + 0x03ad: 0x07b2, // XK_Greek_epsilonaccent + 0x03ae: 0x07b3, // XK_Greek_etaaccent + 0x03af: 0x07b4, // XK_Greek_iotaaccent + 0x03b0: 0x07ba, // XK_Greek_upsilonaccentdieresis + 0x03b1: 0x07e1, // XK_Greek_alpha + 0x03b2: 0x07e2, // XK_Greek_beta + 0x03b3: 0x07e3, // XK_Greek_gamma + 0x03b4: 0x07e4, // XK_Greek_delta + 0x03b5: 0x07e5, // XK_Greek_epsilon + 0x03b6: 0x07e6, // XK_Greek_zeta + 0x03b7: 0x07e7, // XK_Greek_eta + 0x03b8: 0x07e8, // XK_Greek_theta + 0x03b9: 0x07e9, // XK_Greek_iota + 0x03ba: 0x07ea, // XK_Greek_kappa + 0x03bb: 0x07eb, // XK_Greek_lamda + 0x03bc: 0x07ec, // XK_Greek_mu + 0x03bd: 0x07ed, // XK_Greek_nu + 0x03be: 0x07ee, // XK_Greek_xi + 0x03bf: 0x07ef, // XK_Greek_omicron + 0x03c0: 0x07f0, // XK_Greek_pi + 0x03c1: 0x07f1, // XK_Greek_rho + 0x03c2: 0x07f3, // XK_Greek_finalsmallsigma + 0x03c3: 0x07f2, // XK_Greek_sigma + 0x03c4: 0x07f4, // XK_Greek_tau + 0x03c5: 0x07f5, // XK_Greek_upsilon + 0x03c6: 0x07f6, // XK_Greek_phi + 0x03c7: 0x07f7, // XK_Greek_chi + 0x03c8: 0x07f8, // XK_Greek_psi + 0x03c9: 0x07f9, // XK_Greek_omega + 0x03ca: 0x07b5, // XK_Greek_iotadieresis + 0x03cb: 0x07b9, // XK_Greek_upsilondieresis + 0x03cc: 0x07b7, // XK_Greek_omicronaccent + 0x03cd: 0x07b8, // XK_Greek_upsilonaccent + 0x03ce: 0x07bb, // XK_Greek_omegaaccent + 0x0401: 0x06b3, // XK_Cyrillic_IO + 0x0402: 0x06b1, // XK_Serbian_DJE + 0x0403: 0x06b2, // XK_Macedonia_GJE + 0x0404: 0x06b4, // XK_Ukrainian_IE + 0x0405: 0x06b5, // XK_Macedonia_DSE + 0x0406: 0x06b6, // XK_Ukrainian_I + 0x0407: 0x06b7, // XK_Ukrainian_YI + 0x0408: 0x06b8, // XK_Cyrillic_JE + 0x0409: 0x06b9, // XK_Cyrillic_LJE + 0x040a: 0x06ba, // XK_Cyrillic_NJE + 0x040b: 0x06bb, // XK_Serbian_TSHE + 0x040c: 0x06bc, // XK_Macedonia_KJE + 0x040e: 0x06be, // XK_Byelorussian_SHORTU + 0x040f: 0x06bf, // XK_Cyrillic_DZHE + 0x0410: 0x06e1, // XK_Cyrillic_A + 0x0411: 0x06e2, // XK_Cyrillic_BE + 0x0412: 0x06f7, // XK_Cyrillic_VE + 0x0413: 0x06e7, // XK_Cyrillic_GHE + 0x0414: 0x06e4, // XK_Cyrillic_DE + 0x0415: 0x06e5, // XK_Cyrillic_IE + 0x0416: 0x06f6, // XK_Cyrillic_ZHE + 0x0417: 0x06fa, // XK_Cyrillic_ZE + 0x0418: 0x06e9, // XK_Cyrillic_I + 0x0419: 0x06ea, // XK_Cyrillic_SHORTI + 0x041a: 0x06eb, // XK_Cyrillic_KA + 0x041b: 0x06ec, // XK_Cyrillic_EL + 0x041c: 0x06ed, // XK_Cyrillic_EM + 0x041d: 0x06ee, // XK_Cyrillic_EN + 0x041e: 0x06ef, // XK_Cyrillic_O + 0x041f: 0x06f0, // XK_Cyrillic_PE + 0x0420: 0x06f2, // XK_Cyrillic_ER + 0x0421: 0x06f3, // XK_Cyrillic_ES + 0x0422: 0x06f4, // XK_Cyrillic_TE + 0x0423: 0x06f5, // XK_Cyrillic_U + 0x0424: 0x06e6, // XK_Cyrillic_EF + 0x0425: 0x06e8, // XK_Cyrillic_HA + 0x0426: 0x06e3, // XK_Cyrillic_TSE + 0x0427: 0x06fe, // XK_Cyrillic_CHE + 0x0428: 0x06fb, // XK_Cyrillic_SHA + 0x0429: 0x06fd, // XK_Cyrillic_SHCHA + 0x042a: 0x06ff, // XK_Cyrillic_HARDSIGN + 0x042b: 0x06f9, // XK_Cyrillic_YERU + 0x042c: 0x06f8, // XK_Cyrillic_SOFTSIGN + 0x042d: 0x06fc, // XK_Cyrillic_E + 0x042e: 0x06e0, // XK_Cyrillic_YU + 0x042f: 0x06f1, // XK_Cyrillic_YA + 0x0430: 0x06c1, // XK_Cyrillic_a + 0x0431: 0x06c2, // XK_Cyrillic_be + 0x0432: 0x06d7, // XK_Cyrillic_ve + 0x0433: 0x06c7, // XK_Cyrillic_ghe + 0x0434: 0x06c4, // XK_Cyrillic_de + 0x0435: 0x06c5, // XK_Cyrillic_ie + 0x0436: 0x06d6, // XK_Cyrillic_zhe + 0x0437: 0x06da, // XK_Cyrillic_ze + 0x0438: 0x06c9, // XK_Cyrillic_i + 0x0439: 0x06ca, // XK_Cyrillic_shorti + 0x043a: 0x06cb, // XK_Cyrillic_ka + 0x043b: 0x06cc, // XK_Cyrillic_el + 0x043c: 0x06cd, // XK_Cyrillic_em + 0x043d: 0x06ce, // XK_Cyrillic_en + 0x043e: 0x06cf, // XK_Cyrillic_o + 0x043f: 0x06d0, // XK_Cyrillic_pe + 0x0440: 0x06d2, // XK_Cyrillic_er + 0x0441: 0x06d3, // XK_Cyrillic_es + 0x0442: 0x06d4, // XK_Cyrillic_te + 0x0443: 0x06d5, // XK_Cyrillic_u + 0x0444: 0x06c6, // XK_Cyrillic_ef + 0x0445: 0x06c8, // XK_Cyrillic_ha + 0x0446: 0x06c3, // XK_Cyrillic_tse + 0x0447: 0x06de, // XK_Cyrillic_che + 0x0448: 0x06db, // XK_Cyrillic_sha + 0x0449: 0x06dd, // XK_Cyrillic_shcha + 0x044a: 0x06df, // XK_Cyrillic_hardsign + 0x044b: 0x06d9, // XK_Cyrillic_yeru + 0x044c: 0x06d8, // XK_Cyrillic_softsign + 0x044d: 0x06dc, // XK_Cyrillic_e + 0x044e: 0x06c0, // XK_Cyrillic_yu + 0x044f: 0x06d1, // XK_Cyrillic_ya + 0x0451: 0x06a3, // XK_Cyrillic_io + 0x0452: 0x06a1, // XK_Serbian_dje + 0x0453: 0x06a2, // XK_Macedonia_gje + 0x0454: 0x06a4, // XK_Ukrainian_ie + 0x0455: 0x06a5, // XK_Macedonia_dse + 0x0456: 0x06a6, // XK_Ukrainian_i + 0x0457: 0x06a7, // XK_Ukrainian_yi + 0x0458: 0x06a8, // XK_Cyrillic_je + 0x0459: 0x06a9, // XK_Cyrillic_lje + 0x045a: 0x06aa, // XK_Cyrillic_nje + 0x045b: 0x06ab, // XK_Serbian_tshe + 0x045c: 0x06ac, // XK_Macedonia_kje + 0x045e: 0x06ae, // XK_Byelorussian_shortu + 0x045f: 0x06af, // XK_Cyrillic_dzhe + 0x0490: 0x06bd, // XK_Ukrainian_GHE_WITH_UPTURN + 0x0491: 0x06ad, // XK_Ukrainian_ghe_with_upturn + 0x05d0: 0x0ce0, // XK_hebrew_aleph + 0x05d1: 0x0ce1, // XK_hebrew_bet + 0x05d2: 0x0ce2, // XK_hebrew_gimel + 0x05d3: 0x0ce3, // XK_hebrew_dalet + 0x05d4: 0x0ce4, // XK_hebrew_he + 0x05d5: 0x0ce5, // XK_hebrew_waw + 0x05d6: 0x0ce6, // XK_hebrew_zain + 0x05d7: 0x0ce7, // XK_hebrew_chet + 0x05d8: 0x0ce8, // XK_hebrew_tet + 0x05d9: 0x0ce9, // XK_hebrew_yod + 0x05da: 0x0cea, // XK_hebrew_finalkaph + 0x05db: 0x0ceb, // XK_hebrew_kaph + 0x05dc: 0x0cec, // XK_hebrew_lamed + 0x05dd: 0x0ced, // XK_hebrew_finalmem + 0x05de: 0x0cee, // XK_hebrew_mem + 0x05df: 0x0cef, // XK_hebrew_finalnun + 0x05e0: 0x0cf0, // XK_hebrew_nun + 0x05e1: 0x0cf1, // XK_hebrew_samech + 0x05e2: 0x0cf2, // XK_hebrew_ayin + 0x05e3: 0x0cf3, // XK_hebrew_finalpe + 0x05e4: 0x0cf4, // XK_hebrew_pe + 0x05e5: 0x0cf5, // XK_hebrew_finalzade + 0x05e6: 0x0cf6, // XK_hebrew_zade + 0x05e7: 0x0cf7, // XK_hebrew_qoph + 0x05e8: 0x0cf8, // XK_hebrew_resh + 0x05e9: 0x0cf9, // XK_hebrew_shin + 0x05ea: 0x0cfa, // XK_hebrew_taw + 0x060c: 0x05ac, // XK_Arabic_comma + 0x061b: 0x05bb, // XK_Arabic_semicolon + 0x061f: 0x05bf, // XK_Arabic_question_mark + 0x0621: 0x05c1, // XK_Arabic_hamza + 0x0622: 0x05c2, // XK_Arabic_maddaonalef + 0x0623: 0x05c3, // XK_Arabic_hamzaonalef + 0x0624: 0x05c4, // XK_Arabic_hamzaonwaw + 0x0625: 0x05c5, // XK_Arabic_hamzaunderalef + 0x0626: 0x05c6, // XK_Arabic_hamzaonyeh + 0x0627: 0x05c7, // XK_Arabic_alef + 0x0628: 0x05c8, // XK_Arabic_beh + 0x0629: 0x05c9, // XK_Arabic_tehmarbuta + 0x062a: 0x05ca, // XK_Arabic_teh + 0x062b: 0x05cb, // XK_Arabic_theh + 0x062c: 0x05cc, // XK_Arabic_jeem + 0x062d: 0x05cd, // XK_Arabic_hah + 0x062e: 0x05ce, // XK_Arabic_khah + 0x062f: 0x05cf, // XK_Arabic_dal + 0x0630: 0x05d0, // XK_Arabic_thal + 0x0631: 0x05d1, // XK_Arabic_ra + 0x0632: 0x05d2, // XK_Arabic_zain + 0x0633: 0x05d3, // XK_Arabic_seen + 0x0634: 0x05d4, // XK_Arabic_sheen + 0x0635: 0x05d5, // XK_Arabic_sad + 0x0636: 0x05d6, // XK_Arabic_dad + 0x0637: 0x05d7, // XK_Arabic_tah + 0x0638: 0x05d8, // XK_Arabic_zah + 0x0639: 0x05d9, // XK_Arabic_ain + 0x063a: 0x05da, // XK_Arabic_ghain + 0x0640: 0x05e0, // XK_Arabic_tatweel + 0x0641: 0x05e1, // XK_Arabic_feh + 0x0642: 0x05e2, // XK_Arabic_qaf + 0x0643: 0x05e3, // XK_Arabic_kaf + 0x0644: 0x05e4, // XK_Arabic_lam + 0x0645: 0x05e5, // XK_Arabic_meem + 0x0646: 0x05e6, // XK_Arabic_noon + 0x0647: 0x05e7, // XK_Arabic_ha + 0x0648: 0x05e8, // XK_Arabic_waw + 0x0649: 0x05e9, // XK_Arabic_alefmaksura + 0x064a: 0x05ea, // XK_Arabic_yeh + 0x064b: 0x05eb, // XK_Arabic_fathatan + 0x064c: 0x05ec, // XK_Arabic_dammatan + 0x064d: 0x05ed, // XK_Arabic_kasratan + 0x064e: 0x05ee, // XK_Arabic_fatha + 0x064f: 0x05ef, // XK_Arabic_damma + 0x0650: 0x05f0, // XK_Arabic_kasra + 0x0651: 0x05f1, // XK_Arabic_shadda + 0x0652: 0x05f2, // XK_Arabic_sukun + 0x0e01: 0x0da1, // XK_Thai_kokai + 0x0e02: 0x0da2, // XK_Thai_khokhai + 0x0e03: 0x0da3, // XK_Thai_khokhuat + 0x0e04: 0x0da4, // XK_Thai_khokhwai + 0x0e05: 0x0da5, // XK_Thai_khokhon + 0x0e06: 0x0da6, // XK_Thai_khorakhang + 0x0e07: 0x0da7, // XK_Thai_ngongu + 0x0e08: 0x0da8, // XK_Thai_chochan + 0x0e09: 0x0da9, // XK_Thai_choching + 0x0e0a: 0x0daa, // XK_Thai_chochang + 0x0e0b: 0x0dab, // XK_Thai_soso + 0x0e0c: 0x0dac, // XK_Thai_chochoe + 0x0e0d: 0x0dad, // XK_Thai_yoying + 0x0e0e: 0x0dae, // XK_Thai_dochada + 0x0e0f: 0x0daf, // XK_Thai_topatak + 0x0e10: 0x0db0, // XK_Thai_thothan + 0x0e11: 0x0db1, // XK_Thai_thonangmontho + 0x0e12: 0x0db2, // XK_Thai_thophuthao + 0x0e13: 0x0db3, // XK_Thai_nonen + 0x0e14: 0x0db4, // XK_Thai_dodek + 0x0e15: 0x0db5, // XK_Thai_totao + 0x0e16: 0x0db6, // XK_Thai_thothung + 0x0e17: 0x0db7, // XK_Thai_thothahan + 0x0e18: 0x0db8, // XK_Thai_thothong + 0x0e19: 0x0db9, // XK_Thai_nonu + 0x0e1a: 0x0dba, // XK_Thai_bobaimai + 0x0e1b: 0x0dbb, // XK_Thai_popla + 0x0e1c: 0x0dbc, // XK_Thai_phophung + 0x0e1d: 0x0dbd, // XK_Thai_fofa + 0x0e1e: 0x0dbe, // XK_Thai_phophan + 0x0e1f: 0x0dbf, // XK_Thai_fofan + 0x0e20: 0x0dc0, // XK_Thai_phosamphao + 0x0e21: 0x0dc1, // XK_Thai_moma + 0x0e22: 0x0dc2, // XK_Thai_yoyak + 0x0e23: 0x0dc3, // XK_Thai_rorua + 0x0e24: 0x0dc4, // XK_Thai_ru + 0x0e25: 0x0dc5, // XK_Thai_loling + 0x0e26: 0x0dc6, // XK_Thai_lu + 0x0e27: 0x0dc7, // XK_Thai_wowaen + 0x0e28: 0x0dc8, // XK_Thai_sosala + 0x0e29: 0x0dc9, // XK_Thai_sorusi + 0x0e2a: 0x0dca, // XK_Thai_sosua + 0x0e2b: 0x0dcb, // XK_Thai_hohip + 0x0e2c: 0x0dcc, // XK_Thai_lochula + 0x0e2d: 0x0dcd, // XK_Thai_oang + 0x0e2e: 0x0dce, // XK_Thai_honokhuk + 0x0e2f: 0x0dcf, // XK_Thai_paiyannoi + 0x0e30: 0x0dd0, // XK_Thai_saraa + 0x0e31: 0x0dd1, // XK_Thai_maihanakat + 0x0e32: 0x0dd2, // XK_Thai_saraaa + 0x0e33: 0x0dd3, // XK_Thai_saraam + 0x0e34: 0x0dd4, // XK_Thai_sarai + 0x0e35: 0x0dd5, // XK_Thai_saraii + 0x0e36: 0x0dd6, // XK_Thai_saraue + 0x0e37: 0x0dd7, // XK_Thai_sarauee + 0x0e38: 0x0dd8, // XK_Thai_sarau + 0x0e39: 0x0dd9, // XK_Thai_sarauu + 0x0e3a: 0x0dda, // XK_Thai_phinthu + 0x0e3f: 0x0ddf, // XK_Thai_baht + 0x0e40: 0x0de0, // XK_Thai_sarae + 0x0e41: 0x0de1, // XK_Thai_saraae + 0x0e42: 0x0de2, // XK_Thai_sarao + 0x0e43: 0x0de3, // XK_Thai_saraaimaimuan + 0x0e44: 0x0de4, // XK_Thai_saraaimaimalai + 0x0e45: 0x0de5, // XK_Thai_lakkhangyao + 0x0e46: 0x0de6, // XK_Thai_maiyamok + 0x0e47: 0x0de7, // XK_Thai_maitaikhu + 0x0e48: 0x0de8, // XK_Thai_maiek + 0x0e49: 0x0de9, // XK_Thai_maitho + 0x0e4a: 0x0dea, // XK_Thai_maitri + 0x0e4b: 0x0deb, // XK_Thai_maichattawa + 0x0e4c: 0x0dec, // XK_Thai_thanthakhat + 0x0e4d: 0x0ded, // XK_Thai_nikhahit + 0x0e50: 0x0df0, // XK_Thai_leksun + 0x0e51: 0x0df1, // XK_Thai_leknung + 0x0e52: 0x0df2, // XK_Thai_leksong + 0x0e53: 0x0df3, // XK_Thai_leksam + 0x0e54: 0x0df4, // XK_Thai_leksi + 0x0e55: 0x0df5, // XK_Thai_lekha + 0x0e56: 0x0df6, // XK_Thai_lekhok + 0x0e57: 0x0df7, // XK_Thai_lekchet + 0x0e58: 0x0df8, // XK_Thai_lekpaet + 0x0e59: 0x0df9, // XK_Thai_lekkao + 0x2002: 0x0aa2, // XK_enspace + 0x2003: 0x0aa1, // XK_emspace + 0x2004: 0x0aa3, // XK_em3space + 0x2005: 0x0aa4, // XK_em4space + 0x2007: 0x0aa5, // XK_digitspace + 0x2008: 0x0aa6, // XK_punctspace + 0x2009: 0x0aa7, // XK_thinspace + 0x200a: 0x0aa8, // XK_hairspace + 0x2012: 0x0abb, // XK_figdash + 0x2013: 0x0aaa, // XK_endash + 0x2014: 0x0aa9, // XK_emdash + 0x2015: 0x07af, // XK_Greek_horizbar + 0x2017: 0x0cdf, // XK_hebrew_doublelowline + 0x2018: 0x0ad0, // XK_leftsinglequotemark + 0x2019: 0x0ad1, // XK_rightsinglequotemark + 0x201a: 0x0afd, // XK_singlelowquotemark + 0x201c: 0x0ad2, // XK_leftdoublequotemark + 0x201d: 0x0ad3, // XK_rightdoublequotemark + 0x201e: 0x0afe, // XK_doublelowquotemark + 0x2020: 0x0af1, // XK_dagger + 0x2021: 0x0af2, // XK_doubledagger + 0x2022: 0x0ae6, // XK_enfilledcircbullet + 0x2025: 0x0aaf, // XK_doubbaselinedot + 0x2026: 0x0aae, // XK_ellipsis + 0x2030: 0x0ad5, // XK_permille + 0x2032: 0x0ad6, // XK_minutes + 0x2033: 0x0ad7, // XK_seconds + 0x2038: 0x0afc, // XK_caret + 0x203e: 0x047e, // XK_overline + 0x20a9: 0x0eff, // XK_Korean_Won + 0x20ac: 0x20ac, // XK_EuroSign + 0x2105: 0x0ab8, // XK_careof + 0x2116: 0x06b0, // XK_numerosign + 0x2117: 0x0afb, // XK_phonographcopyright + 0x211e: 0x0ad4, // XK_prescription + 0x2122: 0x0ac9, // XK_trademark + 0x2153: 0x0ab0, // XK_onethird + 0x2154: 0x0ab1, // XK_twothirds + 0x2155: 0x0ab2, // XK_onefifth + 0x2156: 0x0ab3, // XK_twofifths + 0x2157: 0x0ab4, // XK_threefifths + 0x2158: 0x0ab5, // XK_fourfifths + 0x2159: 0x0ab6, // XK_onesixth + 0x215a: 0x0ab7, // XK_fivesixths + 0x215b: 0x0ac3, // XK_oneeighth + 0x215c: 0x0ac4, // XK_threeeighths + 0x215d: 0x0ac5, // XK_fiveeighths + 0x215e: 0x0ac6, // XK_seveneighths + 0x2190: 0x08fb, // XK_leftarrow + 0x2191: 0x08fc, // XK_uparrow + 0x2192: 0x08fd, // XK_rightarrow + 0x2193: 0x08fe, // XK_downarrow + 0x21d2: 0x08ce, // XK_implies + 0x21d4: 0x08cd, // XK_ifonlyif + 0x2202: 0x08ef, // XK_partialderivative + 0x2207: 0x08c5, // XK_nabla + 0x2218: 0x0bca, // XK_jot + 0x221a: 0x08d6, // XK_radical + 0x221d: 0x08c1, // XK_variation + 0x221e: 0x08c2, // XK_infinity + 0x2227: 0x08de, // XK_logicaland + 0x2228: 0x08df, // XK_logicalor + 0x2229: 0x08dc, // XK_intersection + 0x222a: 0x08dd, // XK_union + 0x222b: 0x08bf, // XK_integral + 0x2234: 0x08c0, // XK_therefore + 0x223c: 0x08c8, // XK_approximate + 0x2243: 0x08c9, // XK_similarequal + 0x2245: 0x1002248, // XK_approxeq + 0x2260: 0x08bd, // XK_notequal + 0x2261: 0x08cf, // XK_identical + 0x2264: 0x08bc, // XK_lessthanequal + 0x2265: 0x08be, // XK_greaterthanequal + 0x2282: 0x08da, // XK_includedin + 0x2283: 0x08db, // XK_includes + 0x22a2: 0x0bfc, // XK_righttack + 0x22a3: 0x0bdc, // XK_lefttack + 0x22a4: 0x0bc2, // XK_downtack + 0x22a5: 0x0bce, // XK_uptack + 0x2308: 0x0bd3, // XK_upstile + 0x230a: 0x0bc4, // XK_downstile + 0x2315: 0x0afa, // XK_telephonerecorder + 0x2320: 0x08a4, // XK_topintegral + 0x2321: 0x08a5, // XK_botintegral + 0x2395: 0x0bcc, // XK_quad + 0x239b: 0x08ab, // XK_topleftparens + 0x239d: 0x08ac, // XK_botleftparens + 0x239e: 0x08ad, // XK_toprightparens + 0x23a0: 0x08ae, // XK_botrightparens + 0x23a1: 0x08a7, // XK_topleftsqbracket + 0x23a3: 0x08a8, // XK_botleftsqbracket + 0x23a4: 0x08a9, // XK_toprightsqbracket + 0x23a6: 0x08aa, // XK_botrightsqbracket + 0x23a8: 0x08af, // XK_leftmiddlecurlybrace + 0x23ac: 0x08b0, // XK_rightmiddlecurlybrace + 0x23b7: 0x08a1, // XK_leftradical + 0x23ba: 0x09ef, // XK_horizlinescan1 + 0x23bb: 0x09f0, // XK_horizlinescan3 + 0x23bc: 0x09f2, // XK_horizlinescan7 + 0x23bd: 0x09f3, // XK_horizlinescan9 + 0x2409: 0x09e2, // XK_ht + 0x240a: 0x09e5, // XK_lf + 0x240b: 0x09e9, // XK_vt + 0x240c: 0x09e3, // XK_ff + 0x240d: 0x09e4, // XK_cr + 0x2423: 0x0aac, // XK_signifblank + 0x2424: 0x09e8, // XK_nl + 0x2500: 0x08a3, // XK_horizconnector + 0x2502: 0x08a6, // XK_vertconnector + 0x250c: 0x08a2, // XK_topleftradical + 0x2510: 0x09eb, // XK_uprightcorner + 0x2514: 0x09ed, // XK_lowleftcorner + 0x2518: 0x09ea, // XK_lowrightcorner + 0x251c: 0x09f4, // XK_leftt + 0x2524: 0x09f5, // XK_rightt + 0x252c: 0x09f7, // XK_topt + 0x2534: 0x09f6, // XK_bott + 0x253c: 0x09ee, // XK_crossinglines + 0x2592: 0x09e1, // XK_checkerboard + 0x25aa: 0x0ae7, // XK_enfilledsqbullet + 0x25ab: 0x0ae1, // XK_enopensquarebullet + 0x25ac: 0x0adb, // XK_filledrectbullet + 0x25ad: 0x0ae2, // XK_openrectbullet + 0x25ae: 0x0adf, // XK_emfilledrect + 0x25af: 0x0acf, // XK_emopenrectangle + 0x25b2: 0x0ae8, // XK_filledtribulletup + 0x25b3: 0x0ae3, // XK_opentribulletup + 0x25b6: 0x0add, // XK_filledrighttribullet + 0x25b7: 0x0acd, // XK_rightopentriangle + 0x25bc: 0x0ae9, // XK_filledtribulletdown + 0x25bd: 0x0ae4, // XK_opentribulletdown + 0x25c0: 0x0adc, // XK_filledlefttribullet + 0x25c1: 0x0acc, // XK_leftopentriangle + 0x25c6: 0x09e0, // XK_soliddiamond + 0x25cb: 0x0ace, // XK_emopencircle + 0x25cf: 0x0ade, // XK_emfilledcircle + 0x25e6: 0x0ae0, // XK_enopencircbullet + 0x2606: 0x0ae5, // XK_openstar + 0x260e: 0x0af9, // XK_telephone + 0x2613: 0x0aca, // XK_signaturemark + 0x261c: 0x0aea, // XK_leftpointer + 0x261e: 0x0aeb, // XK_rightpointer + 0x2640: 0x0af8, // XK_femalesymbol + 0x2642: 0x0af7, // XK_malesymbol + 0x2663: 0x0aec, // XK_club + 0x2665: 0x0aee, // XK_heart + 0x2666: 0x0aed, // XK_diamond + 0x266d: 0x0af6, // XK_musicalflat + 0x266f: 0x0af5, // XK_musicalsharp + 0x2713: 0x0af3, // XK_checkmark + 0x2717: 0x0af4, // XK_ballotcross + 0x271d: 0x0ad9, // XK_latincross + 0x2720: 0x0af0, // XK_maltesecross + 0x27e8: 0x0abc, // XK_leftanglebracket + 0x27e9: 0x0abe, // XK_rightanglebracket + 0x3001: 0x04a4, // XK_kana_comma + 0x3002: 0x04a1, // XK_kana_fullstop + 0x300c: 0x04a2, // XK_kana_openingbracket + 0x300d: 0x04a3, // XK_kana_closingbracket + 0x309b: 0x04de, // XK_voicedsound + 0x309c: 0x04df, // XK_semivoicedsound + 0x30a1: 0x04a7, // XK_kana_a + 0x30a2: 0x04b1, // XK_kana_A + 0x30a3: 0x04a8, // XK_kana_i + 0x30a4: 0x04b2, // XK_kana_I + 0x30a5: 0x04a9, // XK_kana_u + 0x30a6: 0x04b3, // XK_kana_U + 0x30a7: 0x04aa, // XK_kana_e + 0x30a8: 0x04b4, // XK_kana_E + 0x30a9: 0x04ab, // XK_kana_o + 0x30aa: 0x04b5, // XK_kana_O + 0x30ab: 0x04b6, // XK_kana_KA + 0x30ad: 0x04b7, // XK_kana_KI + 0x30af: 0x04b8, // XK_kana_KU + 0x30b1: 0x04b9, // XK_kana_KE + 0x30b3: 0x04ba, // XK_kana_KO + 0x30b5: 0x04bb, // XK_kana_SA + 0x30b7: 0x04bc, // XK_kana_SHI + 0x30b9: 0x04bd, // XK_kana_SU + 0x30bb: 0x04be, // XK_kana_SE + 0x30bd: 0x04bf, // XK_kana_SO + 0x30bf: 0x04c0, // XK_kana_TA + 0x30c1: 0x04c1, // XK_kana_CHI + 0x30c3: 0x04af, // XK_kana_tsu + 0x30c4: 0x04c2, // XK_kana_TSU + 0x30c6: 0x04c3, // XK_kana_TE + 0x30c8: 0x04c4, // XK_kana_TO + 0x30ca: 0x04c5, // XK_kana_NA + 0x30cb: 0x04c6, // XK_kana_NI + 0x30cc: 0x04c7, // XK_kana_NU + 0x30cd: 0x04c8, // XK_kana_NE + 0x30ce: 0x04c9, // XK_kana_NO + 0x30cf: 0x04ca, // XK_kana_HA + 0x30d2: 0x04cb, // XK_kana_HI + 0x30d5: 0x04cc, // XK_kana_FU + 0x30d8: 0x04cd, // XK_kana_HE + 0x30db: 0x04ce, // XK_kana_HO + 0x30de: 0x04cf, // XK_kana_MA + 0x30df: 0x04d0, // XK_kana_MI + 0x30e0: 0x04d1, // XK_kana_MU + 0x30e1: 0x04d2, // XK_kana_ME + 0x30e2: 0x04d3, // XK_kana_MO + 0x30e3: 0x04ac, // XK_kana_ya + 0x30e4: 0x04d4, // XK_kana_YA + 0x30e5: 0x04ad, // XK_kana_yu + 0x30e6: 0x04d5, // XK_kana_YU + 0x30e7: 0x04ae, // XK_kana_yo + 0x30e8: 0x04d6, // XK_kana_YO + 0x30e9: 0x04d7, // XK_kana_RA + 0x30ea: 0x04d8, // XK_kana_RI + 0x30eb: 0x04d9, // XK_kana_RU + 0x30ec: 0x04da, // XK_kana_RE + 0x30ed: 0x04db, // XK_kana_RO + 0x30ef: 0x04dc, // XK_kana_WA + 0x30f2: 0x04a6, // XK_kana_WO + 0x30f3: 0x04dd, // XK_kana_N + 0x30fb: 0x04a5, // XK_kana_conjunctive + 0x30fc: 0x04b0, // XK_prolongedsound +}; + +export default { + lookup(u) { + // Latin-1 is one-to-one mapping + if ((u >= 0x20) && (u <= 0xff)) { + return u; + } + + // Lookup table (fairly random) + const keysym = codepoints[u]; + if (keysym !== undefined) { + return keysym; + } + + // General mapping as final fallback + return 0x01000000 | u; + }, +}; diff --git a/engine/static/vendor/novnc/core/input/util.js b/engine/static/vendor/novnc/core/input/util.js new file mode 100644 index 00000000..36b69817 --- /dev/null +++ b/engine/static/vendor/novnc/core/input/util.js @@ -0,0 +1,191 @@ +import KeyTable from "./keysym.js"; +import keysyms from "./keysymdef.js"; +import vkeys from "./vkeys.js"; +import fixedkeys from "./fixedkeys.js"; +import DOMKeyTable from "./domkeytable.js"; +import * as browser from "../util/browser.js"; + +// Get 'KeyboardEvent.code', handling legacy browsers +export function getKeycode(evt) { + // Are we getting proper key identifiers? + // (unfortunately Firefox and Chrome are crappy here and gives + // us an empty string on some platforms, rather than leaving it + // undefined) + if (evt.code) { + // Mozilla isn't fully in sync with the spec yet + switch (evt.code) { + case 'OSLeft': return 'MetaLeft'; + case 'OSRight': return 'MetaRight'; + } + + return evt.code; + } + + // The de-facto standard is to use Windows Virtual-Key codes + // in the 'keyCode' field for non-printable characters + if (evt.keyCode in vkeys) { + let code = vkeys[evt.keyCode]; + + // macOS has messed up this code for some reason + if (browser.isMac() && (code === 'ContextMenu')) { + code = 'MetaRight'; + } + + // The keyCode doesn't distinguish between left and right + // for the standard modifiers + if (evt.location === 2) { + switch (code) { + case 'ShiftLeft': return 'ShiftRight'; + case 'ControlLeft': return 'ControlRight'; + case 'AltLeft': return 'AltRight'; + } + } + + // Nor a bunch of the numpad keys + if (evt.location === 3) { + switch (code) { + case 'Delete': return 'NumpadDecimal'; + case 'Insert': return 'Numpad0'; + case 'End': return 'Numpad1'; + case 'ArrowDown': return 'Numpad2'; + case 'PageDown': return 'Numpad3'; + case 'ArrowLeft': return 'Numpad4'; + case 'ArrowRight': return 'Numpad6'; + case 'Home': return 'Numpad7'; + case 'ArrowUp': return 'Numpad8'; + case 'PageUp': return 'Numpad9'; + case 'Enter': return 'NumpadEnter'; + } + } + + return code; + } + + return 'Unidentified'; +} + +// Get 'KeyboardEvent.key', handling legacy browsers +export function getKey(evt) { + // Are we getting a proper key value? + if ((evt.key !== undefined) && (evt.key !== 'Unidentified')) { + // Mozilla isn't fully in sync with the spec yet + switch (evt.key) { + case 'OS': return 'Meta'; + case 'LaunchMyComputer': return 'LaunchApplication1'; + case 'LaunchCalculator': return 'LaunchApplication2'; + } + + // iOS leaks some OS names + switch (evt.key) { + case 'UIKeyInputUpArrow': return 'ArrowUp'; + case 'UIKeyInputDownArrow': return 'ArrowDown'; + case 'UIKeyInputLeftArrow': return 'ArrowLeft'; + case 'UIKeyInputRightArrow': return 'ArrowRight'; + case 'UIKeyInputEscape': return 'Escape'; + } + + // Broken behaviour in Chrome + if ((evt.key === '\x00') && (evt.code === 'NumpadDecimal')) { + return 'Delete'; + } + + return evt.key; + } + + // Try to deduce it based on the physical key + const code = getKeycode(evt); + if (code in fixedkeys) { + return fixedkeys[code]; + } + + // If that failed, then see if we have a printable character + if (evt.charCode) { + return String.fromCharCode(evt.charCode); + } + + // At this point we have nothing left to go on + return 'Unidentified'; +} + +// Get the most reliable keysym value we can get from a key event +export function getKeysym(evt) { + const key = getKey(evt); + + if (key === 'Unidentified') { + return null; + } + + // First look up special keys + if (key in DOMKeyTable) { + let location = evt.location; + + // Safari screws up location for the right cmd key + if ((key === 'Meta') && (location === 0)) { + location = 2; + } + + // And for Clear + if ((key === 'Clear') && (location === 3)) { + let code = getKeycode(evt); + if (code === 'NumLock') { + location = 0; + } + } + + if ((location === undefined) || (location > 3)) { + location = 0; + } + + // The original Meta key now gets confused with the Windows key + // https://bugs.chromium.org/p/chromium/issues/detail?id=1020141 + // https://bugzilla.mozilla.org/show_bug.cgi?id=1232918 + if (key === 'Meta') { + let code = getKeycode(evt); + if (code === 'AltLeft') { + return KeyTable.XK_Meta_L; + } else if (code === 'AltRight') { + return KeyTable.XK_Meta_R; + } + } + + // macOS has Clear instead of NumLock, but the remote system is + // probably not macOS, so lying here is probably best... + if (key === 'Clear') { + let code = getKeycode(evt); + if (code === 'NumLock') { + return KeyTable.XK_Num_Lock; + } + } + + // Windows sends alternating symbols for some keys when using a + // Japanese layout. We have no way of synchronising with the IM + // running on the remote system, so we send some combined keysym + // instead and hope for the best. + if (browser.isWindows()) { + switch (key) { + case 'Zenkaku': + case 'Hankaku': + return KeyTable.XK_Zenkaku_Hankaku; + case 'Romaji': + case 'KanaMode': + return KeyTable.XK_Romaji; + } + } + + return DOMKeyTable[key][location]; + } + + // Now we need to look at the Unicode symbol instead + + // Special key? (FIXME: Should have been caught earlier) + if (key.length !== 1) { + return null; + } + + const codepoint = key.charCodeAt(); + if (codepoint) { + return keysyms.lookup(codepoint); + } + + return null; +} diff --git a/engine/static/vendor/novnc/core/input/vkeys.js b/engine/static/vendor/novnc/core/input/vkeys.js new file mode 100644 index 00000000..d848337a --- /dev/null +++ b/engine/static/vendor/novnc/core/input/vkeys.js @@ -0,0 +1,116 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +/* + * Mapping between Microsoft® Windows® Virtual-Key codes and + * HTML key codes. + */ + +export default { + 0x08: 'Backspace', + 0x09: 'Tab', + 0x0a: 'NumpadClear', + 0x0d: 'Enter', + 0x10: 'ShiftLeft', + 0x11: 'ControlLeft', + 0x12: 'AltLeft', + 0x13: 'Pause', + 0x14: 'CapsLock', + 0x15: 'Lang1', + 0x19: 'Lang2', + 0x1b: 'Escape', + 0x1c: 'Convert', + 0x1d: 'NonConvert', + 0x20: 'Space', + 0x21: 'PageUp', + 0x22: 'PageDown', + 0x23: 'End', + 0x24: 'Home', + 0x25: 'ArrowLeft', + 0x26: 'ArrowUp', + 0x27: 'ArrowRight', + 0x28: 'ArrowDown', + 0x29: 'Select', + 0x2c: 'PrintScreen', + 0x2d: 'Insert', + 0x2e: 'Delete', + 0x2f: 'Help', + 0x30: 'Digit0', + 0x31: 'Digit1', + 0x32: 'Digit2', + 0x33: 'Digit3', + 0x34: 'Digit4', + 0x35: 'Digit5', + 0x36: 'Digit6', + 0x37: 'Digit7', + 0x38: 'Digit8', + 0x39: 'Digit9', + 0x5b: 'MetaLeft', + 0x5c: 'MetaRight', + 0x5d: 'ContextMenu', + 0x5f: 'Sleep', + 0x60: 'Numpad0', + 0x61: 'Numpad1', + 0x62: 'Numpad2', + 0x63: 'Numpad3', + 0x64: 'Numpad4', + 0x65: 'Numpad5', + 0x66: 'Numpad6', + 0x67: 'Numpad7', + 0x68: 'Numpad8', + 0x69: 'Numpad9', + 0x6a: 'NumpadMultiply', + 0x6b: 'NumpadAdd', + 0x6c: 'NumpadDecimal', + 0x6d: 'NumpadSubtract', + 0x6e: 'NumpadDecimal', // Duplicate, because buggy on Windows + 0x6f: 'NumpadDivide', + 0x70: 'F1', + 0x71: 'F2', + 0x72: 'F3', + 0x73: 'F4', + 0x74: 'F5', + 0x75: 'F6', + 0x76: 'F7', + 0x77: 'F8', + 0x78: 'F9', + 0x79: 'F10', + 0x7a: 'F11', + 0x7b: 'F12', + 0x7c: 'F13', + 0x7d: 'F14', + 0x7e: 'F15', + 0x7f: 'F16', + 0x80: 'F17', + 0x81: 'F18', + 0x82: 'F19', + 0x83: 'F20', + 0x84: 'F21', + 0x85: 'F22', + 0x86: 'F23', + 0x87: 'F24', + 0x90: 'NumLock', + 0x91: 'ScrollLock', + 0xa6: 'BrowserBack', + 0xa7: 'BrowserForward', + 0xa8: 'BrowserRefresh', + 0xa9: 'BrowserStop', + 0xaa: 'BrowserSearch', + 0xab: 'BrowserFavorites', + 0xac: 'BrowserHome', + 0xad: 'AudioVolumeMute', + 0xae: 'AudioVolumeDown', + 0xaf: 'AudioVolumeUp', + 0xb0: 'MediaTrackNext', + 0xb1: 'MediaTrackPrevious', + 0xb2: 'MediaStop', + 0xb3: 'MediaPlayPause', + 0xb4: 'LaunchMail', + 0xb5: 'MediaSelect', + 0xb6: 'LaunchApp1', + 0xb7: 'LaunchApp2', + 0xe1: 'AltRight', // Only when it is AltGraph +}; diff --git a/engine/static/vendor/novnc/core/input/xtscancodes.js b/engine/static/vendor/novnc/core/input/xtscancodes.js new file mode 100644 index 00000000..8ab9c17f --- /dev/null +++ b/engine/static/vendor/novnc/core/input/xtscancodes.js @@ -0,0 +1,173 @@ +/* + * This file is auto-generated from keymaps.csv + * Database checksum sha256(76d68c10e97d37fe2ea459e210125ae41796253fb217e900bf2983ade13a7920) + * To re-generate, run: + * keymap-gen code-map --lang=js keymaps.csv html atset1 +*/ +export default { + "Again": 0xe005, /* html:Again (Again) -> linux:129 (KEY_AGAIN) -> atset1:57349 */ + "AltLeft": 0x38, /* html:AltLeft (AltLeft) -> linux:56 (KEY_LEFTALT) -> atset1:56 */ + "AltRight": 0xe038, /* html:AltRight (AltRight) -> linux:100 (KEY_RIGHTALT) -> atset1:57400 */ + "ArrowDown": 0xe050, /* html:ArrowDown (ArrowDown) -> linux:108 (KEY_DOWN) -> atset1:57424 */ + "ArrowLeft": 0xe04b, /* html:ArrowLeft (ArrowLeft) -> linux:105 (KEY_LEFT) -> atset1:57419 */ + "ArrowRight": 0xe04d, /* html:ArrowRight (ArrowRight) -> linux:106 (KEY_RIGHT) -> atset1:57421 */ + "ArrowUp": 0xe048, /* html:ArrowUp (ArrowUp) -> linux:103 (KEY_UP) -> atset1:57416 */ + "AudioVolumeDown": 0xe02e, /* html:AudioVolumeDown (AudioVolumeDown) -> linux:114 (KEY_VOLUMEDOWN) -> atset1:57390 */ + "AudioVolumeMute": 0xe020, /* html:AudioVolumeMute (AudioVolumeMute) -> linux:113 (KEY_MUTE) -> atset1:57376 */ + "AudioVolumeUp": 0xe030, /* html:AudioVolumeUp (AudioVolumeUp) -> linux:115 (KEY_VOLUMEUP) -> atset1:57392 */ + "Backquote": 0x29, /* html:Backquote (Backquote) -> linux:41 (KEY_GRAVE) -> atset1:41 */ + "Backslash": 0x2b, /* html:Backslash (Backslash) -> linux:43 (KEY_BACKSLASH) -> atset1:43 */ + "Backspace": 0xe, /* html:Backspace (Backspace) -> linux:14 (KEY_BACKSPACE) -> atset1:14 */ + "BracketLeft": 0x1a, /* html:BracketLeft (BracketLeft) -> linux:26 (KEY_LEFTBRACE) -> atset1:26 */ + "BracketRight": 0x1b, /* html:BracketRight (BracketRight) -> linux:27 (KEY_RIGHTBRACE) -> atset1:27 */ + "BrowserBack": 0xe06a, /* html:BrowserBack (BrowserBack) -> linux:158 (KEY_BACK) -> atset1:57450 */ + "BrowserFavorites": 0xe066, /* html:BrowserFavorites (BrowserFavorites) -> linux:156 (KEY_BOOKMARKS) -> atset1:57446 */ + "BrowserForward": 0xe069, /* html:BrowserForward (BrowserForward) -> linux:159 (KEY_FORWARD) -> atset1:57449 */ + "BrowserHome": 0xe032, /* html:BrowserHome (BrowserHome) -> linux:172 (KEY_HOMEPAGE) -> atset1:57394 */ + "BrowserRefresh": 0xe067, /* html:BrowserRefresh (BrowserRefresh) -> linux:173 (KEY_REFRESH) -> atset1:57447 */ + "BrowserSearch": 0xe065, /* html:BrowserSearch (BrowserSearch) -> linux:217 (KEY_SEARCH) -> atset1:57445 */ + "BrowserStop": 0xe068, /* html:BrowserStop (BrowserStop) -> linux:128 (KEY_STOP) -> atset1:57448 */ + "CapsLock": 0x3a, /* html:CapsLock (CapsLock) -> linux:58 (KEY_CAPSLOCK) -> atset1:58 */ + "Comma": 0x33, /* html:Comma (Comma) -> linux:51 (KEY_COMMA) -> atset1:51 */ + "ContextMenu": 0xe05d, /* html:ContextMenu (ContextMenu) -> linux:127 (KEY_COMPOSE) -> atset1:57437 */ + "ControlLeft": 0x1d, /* html:ControlLeft (ControlLeft) -> linux:29 (KEY_LEFTCTRL) -> atset1:29 */ + "ControlRight": 0xe01d, /* html:ControlRight (ControlRight) -> linux:97 (KEY_RIGHTCTRL) -> atset1:57373 */ + "Convert": 0x79, /* html:Convert (Convert) -> linux:92 (KEY_HENKAN) -> atset1:121 */ + "Copy": 0xe078, /* html:Copy (Copy) -> linux:133 (KEY_COPY) -> atset1:57464 */ + "Cut": 0xe03c, /* html:Cut (Cut) -> linux:137 (KEY_CUT) -> atset1:57404 */ + "Delete": 0xe053, /* html:Delete (Delete) -> linux:111 (KEY_DELETE) -> atset1:57427 */ + "Digit0": 0xb, /* html:Digit0 (Digit0) -> linux:11 (KEY_0) -> atset1:11 */ + "Digit1": 0x2, /* html:Digit1 (Digit1) -> linux:2 (KEY_1) -> atset1:2 */ + "Digit2": 0x3, /* html:Digit2 (Digit2) -> linux:3 (KEY_2) -> atset1:3 */ + "Digit3": 0x4, /* html:Digit3 (Digit3) -> linux:4 (KEY_3) -> atset1:4 */ + "Digit4": 0x5, /* html:Digit4 (Digit4) -> linux:5 (KEY_4) -> atset1:5 */ + "Digit5": 0x6, /* html:Digit5 (Digit5) -> linux:6 (KEY_5) -> atset1:6 */ + "Digit6": 0x7, /* html:Digit6 (Digit6) -> linux:7 (KEY_6) -> atset1:7 */ + "Digit7": 0x8, /* html:Digit7 (Digit7) -> linux:8 (KEY_7) -> atset1:8 */ + "Digit8": 0x9, /* html:Digit8 (Digit8) -> linux:9 (KEY_8) -> atset1:9 */ + "Digit9": 0xa, /* html:Digit9 (Digit9) -> linux:10 (KEY_9) -> atset1:10 */ + "Eject": 0xe07d, /* html:Eject (Eject) -> linux:162 (KEY_EJECTCLOSECD) -> atset1:57469 */ + "End": 0xe04f, /* html:End (End) -> linux:107 (KEY_END) -> atset1:57423 */ + "Enter": 0x1c, /* html:Enter (Enter) -> linux:28 (KEY_ENTER) -> atset1:28 */ + "Equal": 0xd, /* html:Equal (Equal) -> linux:13 (KEY_EQUAL) -> atset1:13 */ + "Escape": 0x1, /* html:Escape (Escape) -> linux:1 (KEY_ESC) -> atset1:1 */ + "F1": 0x3b, /* html:F1 (F1) -> linux:59 (KEY_F1) -> atset1:59 */ + "F10": 0x44, /* html:F10 (F10) -> linux:68 (KEY_F10) -> atset1:68 */ + "F11": 0x57, /* html:F11 (F11) -> linux:87 (KEY_F11) -> atset1:87 */ + "F12": 0x58, /* html:F12 (F12) -> linux:88 (KEY_F12) -> atset1:88 */ + "F13": 0x5d, /* html:F13 (F13) -> linux:183 (KEY_F13) -> atset1:93 */ + "F14": 0x5e, /* html:F14 (F14) -> linux:184 (KEY_F14) -> atset1:94 */ + "F15": 0x5f, /* html:F15 (F15) -> linux:185 (KEY_F15) -> atset1:95 */ + "F16": 0x55, /* html:F16 (F16) -> linux:186 (KEY_F16) -> atset1:85 */ + "F17": 0xe003, /* html:F17 (F17) -> linux:187 (KEY_F17) -> atset1:57347 */ + "F18": 0xe077, /* html:F18 (F18) -> linux:188 (KEY_F18) -> atset1:57463 */ + "F19": 0xe004, /* html:F19 (F19) -> linux:189 (KEY_F19) -> atset1:57348 */ + "F2": 0x3c, /* html:F2 (F2) -> linux:60 (KEY_F2) -> atset1:60 */ + "F20": 0x5a, /* html:F20 (F20) -> linux:190 (KEY_F20) -> atset1:90 */ + "F21": 0x74, /* html:F21 (F21) -> linux:191 (KEY_F21) -> atset1:116 */ + "F22": 0xe079, /* html:F22 (F22) -> linux:192 (KEY_F22) -> atset1:57465 */ + "F23": 0x6d, /* html:F23 (F23) -> linux:193 (KEY_F23) -> atset1:109 */ + "F24": 0x6f, /* html:F24 (F24) -> linux:194 (KEY_F24) -> atset1:111 */ + "F3": 0x3d, /* html:F3 (F3) -> linux:61 (KEY_F3) -> atset1:61 */ + "F4": 0x3e, /* html:F4 (F4) -> linux:62 (KEY_F4) -> atset1:62 */ + "F5": 0x3f, /* html:F5 (F5) -> linux:63 (KEY_F5) -> atset1:63 */ + "F6": 0x40, /* html:F6 (F6) -> linux:64 (KEY_F6) -> atset1:64 */ + "F7": 0x41, /* html:F7 (F7) -> linux:65 (KEY_F7) -> atset1:65 */ + "F8": 0x42, /* html:F8 (F8) -> linux:66 (KEY_F8) -> atset1:66 */ + "F9": 0x43, /* html:F9 (F9) -> linux:67 (KEY_F9) -> atset1:67 */ + "Find": 0xe041, /* html:Find (Find) -> linux:136 (KEY_FIND) -> atset1:57409 */ + "Help": 0xe075, /* html:Help (Help) -> linux:138 (KEY_HELP) -> atset1:57461 */ + "Hiragana": 0x77, /* html:Hiragana (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */ + "Home": 0xe047, /* html:Home (Home) -> linux:102 (KEY_HOME) -> atset1:57415 */ + "Insert": 0xe052, /* html:Insert (Insert) -> linux:110 (KEY_INSERT) -> atset1:57426 */ + "IntlBackslash": 0x56, /* html:IntlBackslash (IntlBackslash) -> linux:86 (KEY_102ND) -> atset1:86 */ + "IntlRo": 0x73, /* html:IntlRo (IntlRo) -> linux:89 (KEY_RO) -> atset1:115 */ + "IntlYen": 0x7d, /* html:IntlYen (IntlYen) -> linux:124 (KEY_YEN) -> atset1:125 */ + "KanaMode": 0x70, /* html:KanaMode (KanaMode) -> linux:93 (KEY_KATAKANAHIRAGANA) -> atset1:112 */ + "Katakana": 0x78, /* html:Katakana (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */ + "KeyA": 0x1e, /* html:KeyA (KeyA) -> linux:30 (KEY_A) -> atset1:30 */ + "KeyB": 0x30, /* html:KeyB (KeyB) -> linux:48 (KEY_B) -> atset1:48 */ + "KeyC": 0x2e, /* html:KeyC (KeyC) -> linux:46 (KEY_C) -> atset1:46 */ + "KeyD": 0x20, /* html:KeyD (KeyD) -> linux:32 (KEY_D) -> atset1:32 */ + "KeyE": 0x12, /* html:KeyE (KeyE) -> linux:18 (KEY_E) -> atset1:18 */ + "KeyF": 0x21, /* html:KeyF (KeyF) -> linux:33 (KEY_F) -> atset1:33 */ + "KeyG": 0x22, /* html:KeyG (KeyG) -> linux:34 (KEY_G) -> atset1:34 */ + "KeyH": 0x23, /* html:KeyH (KeyH) -> linux:35 (KEY_H) -> atset1:35 */ + "KeyI": 0x17, /* html:KeyI (KeyI) -> linux:23 (KEY_I) -> atset1:23 */ + "KeyJ": 0x24, /* html:KeyJ (KeyJ) -> linux:36 (KEY_J) -> atset1:36 */ + "KeyK": 0x25, /* html:KeyK (KeyK) -> linux:37 (KEY_K) -> atset1:37 */ + "KeyL": 0x26, /* html:KeyL (KeyL) -> linux:38 (KEY_L) -> atset1:38 */ + "KeyM": 0x32, /* html:KeyM (KeyM) -> linux:50 (KEY_M) -> atset1:50 */ + "KeyN": 0x31, /* html:KeyN (KeyN) -> linux:49 (KEY_N) -> atset1:49 */ + "KeyO": 0x18, /* html:KeyO (KeyO) -> linux:24 (KEY_O) -> atset1:24 */ + "KeyP": 0x19, /* html:KeyP (KeyP) -> linux:25 (KEY_P) -> atset1:25 */ + "KeyQ": 0x10, /* html:KeyQ (KeyQ) -> linux:16 (KEY_Q) -> atset1:16 */ + "KeyR": 0x13, /* html:KeyR (KeyR) -> linux:19 (KEY_R) -> atset1:19 */ + "KeyS": 0x1f, /* html:KeyS (KeyS) -> linux:31 (KEY_S) -> atset1:31 */ + "KeyT": 0x14, /* html:KeyT (KeyT) -> linux:20 (KEY_T) -> atset1:20 */ + "KeyU": 0x16, /* html:KeyU (KeyU) -> linux:22 (KEY_U) -> atset1:22 */ + "KeyV": 0x2f, /* html:KeyV (KeyV) -> linux:47 (KEY_V) -> atset1:47 */ + "KeyW": 0x11, /* html:KeyW (KeyW) -> linux:17 (KEY_W) -> atset1:17 */ + "KeyX": 0x2d, /* html:KeyX (KeyX) -> linux:45 (KEY_X) -> atset1:45 */ + "KeyY": 0x15, /* html:KeyY (KeyY) -> linux:21 (KEY_Y) -> atset1:21 */ + "KeyZ": 0x2c, /* html:KeyZ (KeyZ) -> linux:44 (KEY_Z) -> atset1:44 */ + "Lang1": 0x72, /* html:Lang1 (Lang1) -> linux:122 (KEY_HANGEUL) -> atset1:114 */ + "Lang2": 0x71, /* html:Lang2 (Lang2) -> linux:123 (KEY_HANJA) -> atset1:113 */ + "Lang3": 0x78, /* html:Lang3 (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */ + "Lang4": 0x77, /* html:Lang4 (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */ + "Lang5": 0x76, /* html:Lang5 (Lang5) -> linux:85 (KEY_ZENKAKUHANKAKU) -> atset1:118 */ + "LaunchApp1": 0xe06b, /* html:LaunchApp1 (LaunchApp1) -> linux:157 (KEY_COMPUTER) -> atset1:57451 */ + "LaunchApp2": 0xe021, /* html:LaunchApp2 (LaunchApp2) -> linux:140 (KEY_CALC) -> atset1:57377 */ + "LaunchMail": 0xe06c, /* html:LaunchMail (LaunchMail) -> linux:155 (KEY_MAIL) -> atset1:57452 */ + "MediaPlayPause": 0xe022, /* html:MediaPlayPause (MediaPlayPause) -> linux:164 (KEY_PLAYPAUSE) -> atset1:57378 */ + "MediaSelect": 0xe06d, /* html:MediaSelect (MediaSelect) -> linux:226 (KEY_MEDIA) -> atset1:57453 */ + "MediaStop": 0xe024, /* html:MediaStop (MediaStop) -> linux:166 (KEY_STOPCD) -> atset1:57380 */ + "MediaTrackNext": 0xe019, /* html:MediaTrackNext (MediaTrackNext) -> linux:163 (KEY_NEXTSONG) -> atset1:57369 */ + "MediaTrackPrevious": 0xe010, /* html:MediaTrackPrevious (MediaTrackPrevious) -> linux:165 (KEY_PREVIOUSSONG) -> atset1:57360 */ + "MetaLeft": 0xe05b, /* html:MetaLeft (MetaLeft) -> linux:125 (KEY_LEFTMETA) -> atset1:57435 */ + "MetaRight": 0xe05c, /* html:MetaRight (MetaRight) -> linux:126 (KEY_RIGHTMETA) -> atset1:57436 */ + "Minus": 0xc, /* html:Minus (Minus) -> linux:12 (KEY_MINUS) -> atset1:12 */ + "NonConvert": 0x7b, /* html:NonConvert (NonConvert) -> linux:94 (KEY_MUHENKAN) -> atset1:123 */ + "NumLock": 0x45, /* html:NumLock (NumLock) -> linux:69 (KEY_NUMLOCK) -> atset1:69 */ + "Numpad0": 0x52, /* html:Numpad0 (Numpad0) -> linux:82 (KEY_KP0) -> atset1:82 */ + "Numpad1": 0x4f, /* html:Numpad1 (Numpad1) -> linux:79 (KEY_KP1) -> atset1:79 */ + "Numpad2": 0x50, /* html:Numpad2 (Numpad2) -> linux:80 (KEY_KP2) -> atset1:80 */ + "Numpad3": 0x51, /* html:Numpad3 (Numpad3) -> linux:81 (KEY_KP3) -> atset1:81 */ + "Numpad4": 0x4b, /* html:Numpad4 (Numpad4) -> linux:75 (KEY_KP4) -> atset1:75 */ + "Numpad5": 0x4c, /* html:Numpad5 (Numpad5) -> linux:76 (KEY_KP5) -> atset1:76 */ + "Numpad6": 0x4d, /* html:Numpad6 (Numpad6) -> linux:77 (KEY_KP6) -> atset1:77 */ + "Numpad7": 0x47, /* html:Numpad7 (Numpad7) -> linux:71 (KEY_KP7) -> atset1:71 */ + "Numpad8": 0x48, /* html:Numpad8 (Numpad8) -> linux:72 (KEY_KP8) -> atset1:72 */ + "Numpad9": 0x49, /* html:Numpad9 (Numpad9) -> linux:73 (KEY_KP9) -> atset1:73 */ + "NumpadAdd": 0x4e, /* html:NumpadAdd (NumpadAdd) -> linux:78 (KEY_KPPLUS) -> atset1:78 */ + "NumpadComma": 0x7e, /* html:NumpadComma (NumpadComma) -> linux:121 (KEY_KPCOMMA) -> atset1:126 */ + "NumpadDecimal": 0x53, /* html:NumpadDecimal (NumpadDecimal) -> linux:83 (KEY_KPDOT) -> atset1:83 */ + "NumpadDivide": 0xe035, /* html:NumpadDivide (NumpadDivide) -> linux:98 (KEY_KPSLASH) -> atset1:57397 */ + "NumpadEnter": 0xe01c, /* html:NumpadEnter (NumpadEnter) -> linux:96 (KEY_KPENTER) -> atset1:57372 */ + "NumpadEqual": 0x59, /* html:NumpadEqual (NumpadEqual) -> linux:117 (KEY_KPEQUAL) -> atset1:89 */ + "NumpadMultiply": 0x37, /* html:NumpadMultiply (NumpadMultiply) -> linux:55 (KEY_KPASTERISK) -> atset1:55 */ + "NumpadParenLeft": 0xe076, /* html:NumpadParenLeft (NumpadParenLeft) -> linux:179 (KEY_KPLEFTPAREN) -> atset1:57462 */ + "NumpadParenRight": 0xe07b, /* html:NumpadParenRight (NumpadParenRight) -> linux:180 (KEY_KPRIGHTPAREN) -> atset1:57467 */ + "NumpadSubtract": 0x4a, /* html:NumpadSubtract (NumpadSubtract) -> linux:74 (KEY_KPMINUS) -> atset1:74 */ + "Open": 0x64, /* html:Open (Open) -> linux:134 (KEY_OPEN) -> atset1:100 */ + "PageDown": 0xe051, /* html:PageDown (PageDown) -> linux:109 (KEY_PAGEDOWN) -> atset1:57425 */ + "PageUp": 0xe049, /* html:PageUp (PageUp) -> linux:104 (KEY_PAGEUP) -> atset1:57417 */ + "Paste": 0x65, /* html:Paste (Paste) -> linux:135 (KEY_PASTE) -> atset1:101 */ + "Pause": 0xe046, /* html:Pause (Pause) -> linux:119 (KEY_PAUSE) -> atset1:57414 */ + "Period": 0x34, /* html:Period (Period) -> linux:52 (KEY_DOT) -> atset1:52 */ + "Power": 0xe05e, /* html:Power (Power) -> linux:116 (KEY_POWER) -> atset1:57438 */ + "PrintScreen": 0x54, /* html:PrintScreen (PrintScreen) -> linux:99 (KEY_SYSRQ) -> atset1:84 */ + "Props": 0xe006, /* html:Props (Props) -> linux:130 (KEY_PROPS) -> atset1:57350 */ + "Quote": 0x28, /* html:Quote (Quote) -> linux:40 (KEY_APOSTROPHE) -> atset1:40 */ + "ScrollLock": 0x46, /* html:ScrollLock (ScrollLock) -> linux:70 (KEY_SCROLLLOCK) -> atset1:70 */ + "Semicolon": 0x27, /* html:Semicolon (Semicolon) -> linux:39 (KEY_SEMICOLON) -> atset1:39 */ + "ShiftLeft": 0x2a, /* html:ShiftLeft (ShiftLeft) -> linux:42 (KEY_LEFTSHIFT) -> atset1:42 */ + "ShiftRight": 0x36, /* html:ShiftRight (ShiftRight) -> linux:54 (KEY_RIGHTSHIFT) -> atset1:54 */ + "Slash": 0x35, /* html:Slash (Slash) -> linux:53 (KEY_SLASH) -> atset1:53 */ + "Sleep": 0xe05f, /* html:Sleep (Sleep) -> linux:142 (KEY_SLEEP) -> atset1:57439 */ + "Space": 0x39, /* html:Space (Space) -> linux:57 (KEY_SPACE) -> atset1:57 */ + "Suspend": 0xe025, /* html:Suspend (Suspend) -> linux:205 (KEY_SUSPEND) -> atset1:57381 */ + "Tab": 0xf, /* html:Tab (Tab) -> linux:15 (KEY_TAB) -> atset1:15 */ + "Undo": 0xe007, /* html:Undo (Undo) -> linux:131 (KEY_UNDO) -> atset1:57351 */ + "WakeUp": 0xe063, /* html:WakeUp (WakeUp) -> linux:143 (KEY_WAKEUP) -> atset1:57443 */ +}; diff --git a/engine/static/vendor/novnc/core/ra2.js b/engine/static/vendor/novnc/core/ra2.js new file mode 100644 index 00000000..d330b848 --- /dev/null +++ b/engine/static/vendor/novnc/core/ra2.js @@ -0,0 +1,312 @@ +import { encodeUTF8 } from './util/strings.js'; +import EventTargetMixin from './util/eventtarget.js'; +import legacyCrypto from './crypto/crypto.js'; + +class RA2Cipher { + constructor() { + this._cipher = null; + this._counter = new Uint8Array(16); + } + + async setKey(key) { + this._cipher = await legacyCrypto.importKey( + "raw", key, { name: "AES-EAX" }, false, ["encrypt, decrypt"]); + } + + async makeMessage(message) { + const ad = new Uint8Array([(message.length & 0xff00) >>> 8, message.length & 0xff]); + const encrypted = await legacyCrypto.encrypt({ + name: "AES-EAX", + iv: this._counter, + additionalData: ad, + }, this._cipher, message); + for (let i = 0; i < 16 && this._counter[i]++ === 255; i++); + const res = new Uint8Array(message.length + 2 + 16); + res.set(ad); + res.set(encrypted, 2); + return res; + } + + async receiveMessage(length, encrypted) { + const ad = new Uint8Array([(length & 0xff00) >>> 8, length & 0xff]); + const res = await legacyCrypto.decrypt({ + name: "AES-EAX", + iv: this._counter, + additionalData: ad, + }, this._cipher, encrypted); + for (let i = 0; i < 16 && this._counter[i]++ === 255; i++); + return res; + } +} + +export default class RSAAESAuthenticationState extends EventTargetMixin { + constructor(sock, getCredentials) { + super(); + this._hasStarted = false; + this._checkSock = null; + this._checkCredentials = null; + this._approveServerResolve = null; + this._sockReject = null; + this._credentialsReject = null; + this._approveServerReject = null; + this._sock = sock; + this._getCredentials = getCredentials; + } + + _waitSockAsync(len) { + return new Promise((resolve, reject) => { + const hasData = () => !this._sock.rQwait('RA2', len); + if (hasData()) { + resolve(); + } else { + this._checkSock = () => { + if (hasData()) { + resolve(); + this._checkSock = null; + this._sockReject = null; + } + }; + this._sockReject = reject; + } + }); + } + + _waitApproveKeyAsync() { + return new Promise((resolve, reject) => { + this._approveServerResolve = resolve; + this._approveServerReject = reject; + }); + } + + _waitCredentialsAsync(subtype) { + const hasCredentials = () => { + if (subtype === 1 && this._getCredentials().username !== undefined && + this._getCredentials().password !== undefined) { + return true; + } else if (subtype === 2 && this._getCredentials().password !== undefined) { + return true; + } + return false; + }; + return new Promise((resolve, reject) => { + if (hasCredentials()) { + resolve(); + } else { + this._checkCredentials = () => { + if (hasCredentials()) { + resolve(); + this._checkCredentials = null; + this._credentialsReject = null; + } + }; + this._credentialsReject = reject; + } + }); + } + + checkInternalEvents() { + if (this._checkSock !== null) { + this._checkSock(); + } + if (this._checkCredentials !== null) { + this._checkCredentials(); + } + } + + approveServer() { + if (this._approveServerResolve !== null) { + this._approveServerResolve(); + this._approveServerResolve = null; + } + } + + disconnect() { + if (this._sockReject !== null) { + this._sockReject(new Error("disconnect normally")); + this._sockReject = null; + } + if (this._credentialsReject !== null) { + this._credentialsReject(new Error("disconnect normally")); + this._credentialsReject = null; + } + if (this._approveServerReject !== null) { + this._approveServerReject(new Error("disconnect normally")); + this._approveServerReject = null; + } + } + + async negotiateRA2neAuthAsync() { + this._hasStarted = true; + // 1: Receive server public key + await this._waitSockAsync(4); + const serverKeyLengthBuffer = this._sock.rQpeekBytes(4); + const serverKeyLength = this._sock.rQshift32(); + if (serverKeyLength < 1024) { + throw new Error("RA2: server public key is too short: " + serverKeyLength); + } else if (serverKeyLength > 8192) { + throw new Error("RA2: server public key is too long: " + serverKeyLength); + } + const serverKeyBytes = Math.ceil(serverKeyLength / 8); + await this._waitSockAsync(serverKeyBytes * 2); + const serverN = this._sock.rQshiftBytes(serverKeyBytes); + const serverE = this._sock.rQshiftBytes(serverKeyBytes); + const serverRSACipher = await legacyCrypto.importKey( + "raw", { n: serverN, e: serverE }, { name: "RSA-PKCS1-v1_5" }, false, ["encrypt"]); + const serverPublickey = new Uint8Array(4 + serverKeyBytes * 2); + serverPublickey.set(serverKeyLengthBuffer); + serverPublickey.set(serverN, 4); + serverPublickey.set(serverE, 4 + serverKeyBytes); + + // verify server public key + let approveKey = this._waitApproveKeyAsync(); + this.dispatchEvent(new CustomEvent("serververification", { + detail: { type: "RSA", publickey: serverPublickey } + })); + await approveKey; + + // 2: Send client public key + const clientKeyLength = 2048; + const clientKeyBytes = Math.ceil(clientKeyLength / 8); + const clientRSACipher = (await legacyCrypto.generateKey({ + name: "RSA-PKCS1-v1_5", + modulusLength: clientKeyLength, + publicExponent: new Uint8Array([1, 0, 1]), + }, true, ["encrypt"])).privateKey; + const clientExportedRSAKey = await legacyCrypto.exportKey("raw", clientRSACipher); + const clientN = clientExportedRSAKey.n; + const clientE = clientExportedRSAKey.e; + const clientPublicKey = new Uint8Array(4 + clientKeyBytes * 2); + clientPublicKey[0] = (clientKeyLength & 0xff000000) >>> 24; + clientPublicKey[1] = (clientKeyLength & 0xff0000) >>> 16; + clientPublicKey[2] = (clientKeyLength & 0xff00) >>> 8; + clientPublicKey[3] = clientKeyLength & 0xff; + clientPublicKey.set(clientN, 4); + clientPublicKey.set(clientE, 4 + clientKeyBytes); + this._sock.sQpushBytes(clientPublicKey); + this._sock.flush(); + + // 3: Send client random + const clientRandom = new Uint8Array(16); + window.crypto.getRandomValues(clientRandom); + const clientEncryptedRandom = await legacyCrypto.encrypt( + { name: "RSA-PKCS1-v1_5" }, serverRSACipher, clientRandom); + const clientRandomMessage = new Uint8Array(2 + serverKeyBytes); + clientRandomMessage[0] = (serverKeyBytes & 0xff00) >>> 8; + clientRandomMessage[1] = serverKeyBytes & 0xff; + clientRandomMessage.set(clientEncryptedRandom, 2); + this._sock.sQpushBytes(clientRandomMessage); + this._sock.flush(); + + // 4: Receive server random + await this._waitSockAsync(2); + if (this._sock.rQshift16() !== clientKeyBytes) { + throw new Error("RA2: wrong encrypted message length"); + } + const serverEncryptedRandom = this._sock.rQshiftBytes(clientKeyBytes); + const serverRandom = await legacyCrypto.decrypt( + { name: "RSA-PKCS1-v1_5" }, clientRSACipher, serverEncryptedRandom); + if (serverRandom === null || serverRandom.length !== 16) { + throw new Error("RA2: corrupted server encrypted random"); + } + + // 5: Compute session keys and set ciphers + let clientSessionKey = new Uint8Array(32); + let serverSessionKey = new Uint8Array(32); + clientSessionKey.set(serverRandom); + clientSessionKey.set(clientRandom, 16); + serverSessionKey.set(clientRandom); + serverSessionKey.set(serverRandom, 16); + clientSessionKey = await window.crypto.subtle.digest("SHA-1", clientSessionKey); + clientSessionKey = new Uint8Array(clientSessionKey).slice(0, 16); + serverSessionKey = await window.crypto.subtle.digest("SHA-1", serverSessionKey); + serverSessionKey = new Uint8Array(serverSessionKey).slice(0, 16); + const clientCipher = new RA2Cipher(); + await clientCipher.setKey(clientSessionKey); + const serverCipher = new RA2Cipher(); + await serverCipher.setKey(serverSessionKey); + + // 6: Compute and exchange hashes + let serverHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2); + let clientHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2); + serverHash.set(serverPublickey); + serverHash.set(clientPublicKey, 4 + serverKeyBytes * 2); + clientHash.set(clientPublicKey); + clientHash.set(serverPublickey, 4 + clientKeyBytes * 2); + serverHash = await window.crypto.subtle.digest("SHA-1", serverHash); + clientHash = await window.crypto.subtle.digest("SHA-1", clientHash); + serverHash = new Uint8Array(serverHash); + clientHash = new Uint8Array(clientHash); + this._sock.sQpushBytes(await clientCipher.makeMessage(clientHash)); + this._sock.flush(); + await this._waitSockAsync(2 + 20 + 16); + if (this._sock.rQshift16() !== 20) { + throw new Error("RA2: wrong server hash"); + } + const serverHashReceived = await serverCipher.receiveMessage( + 20, this._sock.rQshiftBytes(20 + 16)); + if (serverHashReceived === null) { + throw new Error("RA2: failed to authenticate the message"); + } + for (let i = 0; i < 20; i++) { + if (serverHashReceived[i] !== serverHash[i]) { + throw new Error("RA2: wrong server hash"); + } + } + + // 7: Receive subtype + await this._waitSockAsync(2 + 1 + 16); + if (this._sock.rQshift16() !== 1) { + throw new Error("RA2: wrong subtype"); + } + let subtype = (await serverCipher.receiveMessage( + 1, this._sock.rQshiftBytes(1 + 16))); + if (subtype === null) { + throw new Error("RA2: failed to authenticate the message"); + } + subtype = subtype[0]; + let waitCredentials = this._waitCredentialsAsync(subtype); + if (subtype === 1) { + if (this._getCredentials().username === undefined || + this._getCredentials().password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + } + } else if (subtype === 2) { + if (this._getCredentials().password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["password"] } })); + } + } else { + throw new Error("RA2: wrong subtype"); + } + await waitCredentials; + let username; + if (subtype === 1) { + username = encodeUTF8(this._getCredentials().username).slice(0, 255); + } else { + username = ""; + } + const password = encodeUTF8(this._getCredentials().password).slice(0, 255); + const credentials = new Uint8Array(username.length + password.length + 2); + credentials[0] = username.length; + credentials[username.length + 1] = password.length; + for (let i = 0; i < username.length; i++) { + credentials[i + 1] = username.charCodeAt(i); + } + for (let i = 0; i < password.length; i++) { + credentials[username.length + 2 + i] = password.charCodeAt(i); + } + this._sock.sQpushBytes(await clientCipher.makeMessage(credentials)); + this._sock.flush(); + } + + get hasStarted() { + return this._hasStarted; + } + + set hasStarted(s) { + this._hasStarted = s; + } +} diff --git a/engine/static/vendor/novnc/core/rfb.js b/engine/static/vendor/novnc/core/rfb.js new file mode 100644 index 00000000..80011e4a --- /dev/null +++ b/engine/static/vendor/novnc/core/rfb.js @@ -0,0 +1,3411 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import { toUnsigned32bit, toSigned32bit } from './util/int.js'; +import * as Log from './util/logging.js'; +import { encodeUTF8, decodeUTF8 } from './util/strings.js'; +import { dragThreshold, supportsWebCodecsH264Decode } from './util/browser.js'; +import { clientToElement } from './util/element.js'; +import { setCapture } from './util/events.js'; +import EventTargetMixin from './util/eventtarget.js'; +import Display from "./display.js"; +import Inflator from "./inflator.js"; +import Deflator from "./deflator.js"; +import Keyboard from "./input/keyboard.js"; +import GestureHandler from "./input/gesturehandler.js"; +import Cursor from "./util/cursor.js"; +import Websock from "./websock.js"; +import KeyTable from "./input/keysym.js"; +import XtScancode from "./input/xtscancodes.js"; +import { encodings } from "./encodings.js"; +import RSAAESAuthenticationState from "./ra2.js"; +import legacyCrypto from "./crypto/crypto.js"; + +import RawDecoder from "./decoders/raw.js"; +import CopyRectDecoder from "./decoders/copyrect.js"; +import RREDecoder from "./decoders/rre.js"; +import HextileDecoder from "./decoders/hextile.js"; +import ZlibDecoder from './decoders/zlib.js'; +import TightDecoder from "./decoders/tight.js"; +import TightPNGDecoder from "./decoders/tightpng.js"; +import ZRLEDecoder from "./decoders/zrle.js"; +import JPEGDecoder from "./decoders/jpeg.js"; +import H264Decoder from "./decoders/h264.js"; + +// How many seconds to wait for a disconnect to finish +const DISCONNECT_TIMEOUT = 3; +const DEFAULT_BACKGROUND = 'rgb(40, 40, 40)'; + +// Minimum wait (ms) between two mouse moves +const MOUSE_MOVE_DELAY = 17; + +// Wheel thresholds +const WHEEL_STEP = 50; // Pixels needed for one step +const WHEEL_LINE_HEIGHT = 19; // Assumed pixels for one line step + +// Gesture thresholds +const GESTURE_ZOOMSENS = 75; +const GESTURE_SCRLSENS = 50; +const DOUBLE_TAP_TIMEOUT = 1000; +const DOUBLE_TAP_THRESHOLD = 50; + +// Security types +const securityTypeNone = 1; +const securityTypeVNCAuth = 2; +const securityTypeRA2ne = 6; +const securityTypeTight = 16; +const securityTypeVeNCrypt = 19; +const securityTypeXVP = 22; +const securityTypeARD = 30; +const securityTypeMSLogonII = 113; + +// Special Tight security types +const securityTypeUnixLogon = 129; + +// VeNCrypt security types +const securityTypePlain = 256; + +// Extended clipboard pseudo-encoding formats +const extendedClipboardFormatText = 1; +/*eslint-disable no-unused-vars */ +const extendedClipboardFormatRtf = 1 << 1; +const extendedClipboardFormatHtml = 1 << 2; +const extendedClipboardFormatDib = 1 << 3; +const extendedClipboardFormatFiles = 1 << 4; +/*eslint-enable */ + +// Extended clipboard pseudo-encoding actions +const extendedClipboardActionCaps = 1 << 24; +const extendedClipboardActionRequest = 1 << 25; +const extendedClipboardActionPeek = 1 << 26; +const extendedClipboardActionNotify = 1 << 27; +const extendedClipboardActionProvide = 1 << 28; + +export default class RFB extends EventTargetMixin { + constructor(target, urlOrChannel, options) { + if (!target) { + throw new Error("Must specify target"); + } + if (!urlOrChannel) { + throw new Error("Must specify URL, WebSocket or RTCDataChannel"); + } + + // We rely on modern APIs which might not be available in an + // insecure context + if (!window.isSecureContext) { + Log.Error("noVNC requires a secure context (TLS). Expect crashes!"); + } + + super(); + + this._target = target; + + if (typeof urlOrChannel === "string") { + this._url = urlOrChannel; + } else { + this._url = null; + this._rawChannel = urlOrChannel; + } + + // Connection details + options = options || {}; + this._rfbCredentials = options.credentials || {}; + this._shared = 'shared' in options ? !!options.shared : true; + this._repeaterID = options.repeaterID || ''; + this._wsProtocols = options.wsProtocols || []; + + // Internal state + this._rfbConnectionState = ''; + this._rfbInitState = ''; + this._rfbAuthScheme = -1; + this._rfbCleanDisconnect = true; + this._rfbRSAAESAuthenticationState = null; + + // Server capabilities + this._rfbVersion = 0; + this._rfbMaxVersion = 3.8; + this._rfbTightVNC = false; + this._rfbVeNCryptState = 0; + this._rfbXvpVer = 0; + + this._fbWidth = 0; + this._fbHeight = 0; + + this._fbName = ""; + + this._capabilities = { power: false }; + + this._supportsFence = false; + + this._supportsContinuousUpdates = false; + this._enabledContinuousUpdates = false; + + this._supportsSetDesktopSize = false; + this._screenID = 0; + this._screenFlags = 0; + this._pendingRemoteResize = false; + this._lastResize = 0; + + this._qemuExtKeyEventSupported = false; + + this._extendedPointerEventSupported = false; + + this._clipboardText = null; + this._clipboardServerCapabilitiesActions = {}; + this._clipboardServerCapabilitiesFormats = {}; + + // Internal objects + this._sock = null; // Websock object + this._display = null; // Display object + this._flushing = false; // Display flushing state + this._keyboard = null; // Keyboard input handler object + this._gestures = null; // Gesture input handler object + this._resizeObserver = null; // Resize observer object + + // Timers + this._disconnTimer = null; // disconnection timer + this._resizeTimeout = null; // resize rate limiting + this._mouseMoveTimer = null; + + // Decoder states + this._decoders = {}; + + this._FBU = { + rects: 0, + x: 0, + y: 0, + width: 0, + height: 0, + encoding: null, + }; + + // Mouse state + this._mousePos = {}; + this._mouseButtonMask = 0; + this._mouseLastMoveTime = 0; + this._viewportDragging = false; + this._viewportDragPos = {}; + this._viewportHasMoved = false; + this._accumulatedWheelDeltaX = 0; + this._accumulatedWheelDeltaY = 0; + + // Gesture state + this._gestureLastTapTime = null; + this._gestureFirstDoubleTapEv = null; + this._gestureLastMagnitudeX = 0; + this._gestureLastMagnitudeY = 0; + + // Bound event handlers + this._eventHandlers = { + focusCanvas: this._focusCanvas.bind(this), + handleResize: this._handleResize.bind(this), + handleMouse: this._handleMouse.bind(this), + handleWheel: this._handleWheel.bind(this), + handleGesture: this._handleGesture.bind(this), + handleRSAAESCredentialsRequired: this._handleRSAAESCredentialsRequired.bind(this), + handleRSAAESServerVerification: this._handleRSAAESServerVerification.bind(this), + }; + + // main setup + Log.Debug(">> RFB.constructor"); + + // Create DOM elements + this._screen = document.createElement('div'); + this._screen.style.display = 'flex'; + this._screen.style.width = '100%'; + this._screen.style.height = '100%'; + this._screen.style.overflow = 'auto'; + this._screen.style.background = DEFAULT_BACKGROUND; + this._canvas = document.createElement('canvas'); + this._canvas.style.margin = 'auto'; + // Some browsers add an outline on focus + this._canvas.style.outline = 'none'; + this._canvas.width = 0; + this._canvas.height = 0; + this._canvas.tabIndex = -1; + this._screen.appendChild(this._canvas); + + // Cursor + this._cursor = new Cursor(); + + // XXX: TightVNC 2.8.11 sends no cursor at all until Windows changes + // it. Result: no cursor at all until a window border or an edit field + // is hit blindly. But there are also VNC servers that draw the cursor + // in the framebuffer and don't send the empty local cursor. There is + // no way to satisfy both sides. + // + // The spec is unclear on this "initial cursor" issue. Many other + // viewers (TigerVNC, RealVNC, Remmina) display an arrow as the + // initial cursor instead. + this._cursorImage = RFB.cursors.none; + + // populate decoder array with objects + this._decoders[encodings.encodingRaw] = new RawDecoder(); + this._decoders[encodings.encodingCopyRect] = new CopyRectDecoder(); + this._decoders[encodings.encodingRRE] = new RREDecoder(); + this._decoders[encodings.encodingHextile] = new HextileDecoder(); + this._decoders[encodings.encodingZlib] = new ZlibDecoder(); + this._decoders[encodings.encodingTight] = new TightDecoder(); + this._decoders[encodings.encodingTightPNG] = new TightPNGDecoder(); + this._decoders[encodings.encodingZRLE] = new ZRLEDecoder(); + this._decoders[encodings.encodingJPEG] = new JPEGDecoder(); + this._decoders[encodings.encodingH264] = new H264Decoder(); + + // NB: nothing that needs explicit teardown should be done + // before this point, since this can throw an exception + try { + this._display = new Display(this._canvas); + } catch (exc) { + Log.Error("Display exception: " + exc); + throw exc; + } + + this._keyboard = new Keyboard(this._canvas); + this._keyboard.onkeyevent = this._handleKeyEvent.bind(this); + this._remoteCapsLock = null; // Null indicates unknown or irrelevant + this._remoteNumLock = null; + + this._gestures = new GestureHandler(); + + this._sock = new Websock(); + this._sock.on('open', this._socketOpen.bind(this)); + this._sock.on('close', this._socketClose.bind(this)); + this._sock.on('message', this._handleMessage.bind(this)); + this._sock.on('error', this._socketError.bind(this)); + + this._expectedClientWidth = null; + this._expectedClientHeight = null; + this._resizeObserver = new ResizeObserver(this._eventHandlers.handleResize); + + // All prepared, kick off the connection + this._updateConnectionState('connecting'); + + Log.Debug("<< RFB.constructor"); + + // ===== PROPERTIES ===== + + this.dragViewport = false; + this.focusOnClick = true; + + this._viewOnly = false; + this._clipViewport = false; + this._clippingViewport = false; + this._scaleViewport = false; + this._resizeSession = false; + + this._showDotCursor = false; + + this._qualityLevel = 6; + this._compressionLevel = 2; + } + + // ===== PROPERTIES ===== + + get viewOnly() { return this._viewOnly; } + set viewOnly(viewOnly) { + this._viewOnly = viewOnly; + + if (this._rfbConnectionState === "connecting" || + this._rfbConnectionState === "connected") { + if (viewOnly) { + this._keyboard.ungrab(); + } else { + this._keyboard.grab(); + } + } + } + + get capabilities() { return this._capabilities; } + + get clippingViewport() { return this._clippingViewport; } + _setClippingViewport(on) { + if (on === this._clippingViewport) { + return; + } + this._clippingViewport = on; + this.dispatchEvent(new CustomEvent("clippingviewport", + { detail: this._clippingViewport })); + } + + get touchButton() { return 0; } + set touchButton(button) { Log.Warn("Using old API!"); } + + get clipViewport() { return this._clipViewport; } + set clipViewport(viewport) { + this._clipViewport = viewport; + this._updateClip(); + } + + get scaleViewport() { return this._scaleViewport; } + set scaleViewport(scale) { + this._scaleViewport = scale; + // Scaling trumps clipping, so we may need to adjust + // clipping when enabling or disabling scaling + if (scale && this._clipViewport) { + this._updateClip(); + } + this._updateScale(); + if (!scale && this._clipViewport) { + this._updateClip(); + } + } + + get resizeSession() { return this._resizeSession; } + set resizeSession(resize) { + this._resizeSession = resize; + if (resize) { + this._requestRemoteResize(); + } + } + + get showDotCursor() { return this._showDotCursor; } + set showDotCursor(show) { + this._showDotCursor = show; + this._refreshCursor(); + } + + get background() { return this._screen.style.background; } + set background(cssValue) { this._screen.style.background = cssValue; } + + get qualityLevel() { + return this._qualityLevel; + } + set qualityLevel(qualityLevel) { + if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { + Log.Error("qualityLevel must be an integer between 0 and 9"); + return; + } + + if (this._qualityLevel === qualityLevel) { + return; + } + + this._qualityLevel = qualityLevel; + + if (this._rfbConnectionState === 'connected') { + this._sendEncodings(); + } + } + + get compressionLevel() { + return this._compressionLevel; + } + set compressionLevel(compressionLevel) { + if (!Number.isInteger(compressionLevel) || compressionLevel < 0 || compressionLevel > 9) { + Log.Error("compressionLevel must be an integer between 0 and 9"); + return; + } + + if (this._compressionLevel === compressionLevel) { + return; + } + + this._compressionLevel = compressionLevel; + + if (this._rfbConnectionState === 'connected') { + this._sendEncodings(); + } + } + + // ===== PUBLIC METHODS ===== + + disconnect() { + this._updateConnectionState('disconnecting'); + this._sock.off('error'); + this._sock.off('message'); + this._sock.off('open'); + if (this._rfbRSAAESAuthenticationState !== null) { + this._rfbRSAAESAuthenticationState.disconnect(); + } + } + + approveServer() { + if (this._rfbRSAAESAuthenticationState !== null) { + this._rfbRSAAESAuthenticationState.approveServer(); + } + } + + sendCredentials(creds) { + this._rfbCredentials = creds; + this._resumeAuthentication(); + } + + sendCtrlAltDel() { + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } + Log.Info("Sending Ctrl-Alt-Del"); + + this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true); + this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true); + this.sendKey(KeyTable.XK_Delete, "Delete", true); + this.sendKey(KeyTable.XK_Delete, "Delete", false); + this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false); + this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false); + } + + machineShutdown() { + this._xvpOp(1, 2); + } + + machineReboot() { + this._xvpOp(1, 3); + } + + machineReset() { + this._xvpOp(1, 4); + } + + // Send a key press. If 'down' is not specified then send a down key + // followed by an up key. + sendKey(keysym, code, down) { + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } + + if (down === undefined) { + this.sendKey(keysym, code, true); + this.sendKey(keysym, code, false); + return; + } + + const scancode = XtScancode[code]; + + if (this._qemuExtKeyEventSupported && scancode) { + // 0 is NoSymbol + keysym = keysym || 0; + + Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode); + + RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode); + } else { + if (!keysym) { + return; + } + Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym); + RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0); + } + } + + focus(options) { + this._canvas.focus(options); + } + + blur() { + this._canvas.blur(); + } + + clipboardPasteFrom(text) { + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } + + if (this._clipboardServerCapabilitiesFormats[extendedClipboardFormatText] && + this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) { + + this._clipboardText = text; + RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]); + } else { + let length, i; + let data; + + length = 0; + // eslint-disable-next-line no-unused-vars + for (let codePoint of text) { + length++; + } + + data = new Uint8Array(length); + + i = 0; + for (let codePoint of text) { + let code = codePoint.codePointAt(0); + + /* Only ISO 8859-1 is supported */ + if (code > 0xff) { + code = 0x3f; // '?' + } + + data[i++] = code; + } + + RFB.messages.clientCutText(this._sock, data); + } + } + + getImageData() { + return this._display.getImageData(); + } + + toDataURL(type, encoderOptions) { + return this._display.toDataURL(type, encoderOptions); + } + + toBlob(callback, type, quality) { + return this._display.toBlob(callback, type, quality); + } + + // ===== PRIVATE METHODS ===== + + _connect() { + Log.Debug(">> RFB.connect"); + + if (this._url) { + Log.Info(`connecting to ${this._url}`); + this._sock.open(this._url, this._wsProtocols); + } else { + Log.Info(`attaching ${this._rawChannel} to Websock`); + this._sock.attach(this._rawChannel); + + if (this._sock.readyState === 'closed') { + throw Error("Cannot use already closed WebSocket/RTCDataChannel"); + } + + if (this._sock.readyState === 'open') { + // FIXME: _socketOpen() can in theory call _fail(), which + // isn't allowed this early, but I'm not sure that can + // happen without a bug messing up our state variables + this._socketOpen(); + } + } + + // Make our elements part of the page + this._target.appendChild(this._screen); + + this._gestures.attach(this._canvas); + + this._cursor.attach(this._canvas); + this._refreshCursor(); + + // Monitor size changes of the screen element + this._resizeObserver.observe(this._screen); + + // Always grab focus on some kind of click event + this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas); + this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas); + + // Mouse events + this._canvas.addEventListener('mousedown', this._eventHandlers.handleMouse); + this._canvas.addEventListener('mouseup', this._eventHandlers.handleMouse); + this._canvas.addEventListener('mousemove', this._eventHandlers.handleMouse); + // Prevent middle-click pasting (see handler for why we bind to document) + this._canvas.addEventListener('click', this._eventHandlers.handleMouse); + // preventDefault() on mousedown doesn't stop this event for some + // reason so we have to explicitly block it + this._canvas.addEventListener('contextmenu', this._eventHandlers.handleMouse); + + // Wheel events + this._canvas.addEventListener("wheel", this._eventHandlers.handleWheel); + + // Gesture events + this._canvas.addEventListener("gesturestart", this._eventHandlers.handleGesture); + this._canvas.addEventListener("gesturemove", this._eventHandlers.handleGesture); + this._canvas.addEventListener("gestureend", this._eventHandlers.handleGesture); + + Log.Debug("<< RFB.connect"); + } + + _disconnect() { + Log.Debug(">> RFB.disconnect"); + this._cursor.detach(); + this._canvas.removeEventListener("gesturestart", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("gesturemove", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("gestureend", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("wheel", this._eventHandlers.handleWheel); + this._canvas.removeEventListener('mousedown', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('mouseup', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('mousemove', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('click', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('contextmenu', this._eventHandlers.handleMouse); + this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas); + this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas); + this._resizeObserver.disconnect(); + this._keyboard.ungrab(); + this._gestures.detach(); + this._sock.close(); + try { + this._target.removeChild(this._screen); + } catch (e) { + if (e.name === 'NotFoundError') { + // Some cases where the initial connection fails + // can disconnect before the _screen is created + } else { + throw e; + } + } + clearTimeout(this._resizeTimeout); + clearTimeout(this._mouseMoveTimer); + Log.Debug("<< RFB.disconnect"); + } + + _socketOpen() { + if ((this._rfbConnectionState === 'connecting') && + (this._rfbInitState === '')) { + this._rfbInitState = 'ProtocolVersion'; + Log.Debug("Starting VNC handshake"); + } else { + this._fail("Unexpected server connection while " + + this._rfbConnectionState); + } + } + + _socketClose(e) { + Log.Debug("WebSocket on-close event"); + let msg = ""; + if (e.code) { + msg = "(code: " + e.code; + if (e.reason) { + msg += ", reason: " + e.reason; + } + msg += ")"; + } + switch (this._rfbConnectionState) { + case 'connecting': + this._fail("Connection closed " + msg); + break; + case 'connected': + // Handle disconnects that were initiated server-side + this._updateConnectionState('disconnecting'); + this._updateConnectionState('disconnected'); + break; + case 'disconnecting': + // Normal disconnection path + this._updateConnectionState('disconnected'); + break; + case 'disconnected': + this._fail("Unexpected server disconnect " + + "when already disconnected " + msg); + break; + default: + this._fail("Unexpected server disconnect before connecting " + + msg); + break; + } + this._sock.off('close'); + // Delete reference to raw channel to allow cleanup. + this._rawChannel = null; + } + + _socketError(e) { + Log.Warn("WebSocket on-error event"); + } + + _focusCanvas(event) { + if (!this.focusOnClick) { + return; + } + + this.focus({ preventScroll: true }); + } + + _setDesktopName(name) { + this._fbName = name; + this.dispatchEvent(new CustomEvent( + "desktopname", + { detail: { name: this._fbName } })); + } + + _saveExpectedClientSize() { + this._expectedClientWidth = this._screen.clientWidth; + this._expectedClientHeight = this._screen.clientHeight; + } + + _currentClientSize() { + return [this._screen.clientWidth, this._screen.clientHeight]; + } + + _clientHasExpectedSize() { + const [currentWidth, currentHeight] = this._currentClientSize(); + return currentWidth == this._expectedClientWidth && + currentHeight == this._expectedClientHeight; + } + + // Handle browser window resizes + _handleResize() { + // Don't change anything if the client size is already as expected + if (this._clientHasExpectedSize()) { + return; + } + // If the window resized then our screen element might have + // as well. Update the viewport dimensions. + window.requestAnimationFrame(() => { + this._updateClip(); + this._updateScale(); + this._saveExpectedClientSize(); + }); + + // Request changing the resolution of the remote display to + // the size of the local browser viewport. + this._requestRemoteResize(); + } + + // Update state of clipping in Display object, and make sure the + // configured viewport matches the current screen size + _updateClip() { + const curClip = this._display.clipViewport; + let newClip = this._clipViewport; + + if (this._scaleViewport) { + // Disable viewport clipping if we are scaling + newClip = false; + } + + if (curClip !== newClip) { + this._display.clipViewport = newClip; + } + + if (newClip) { + // When clipping is enabled, the screen is limited to + // the size of the container. + const size = this._screenSize(); + this._display.viewportChangeSize(size.w, size.h); + this._fixScrollbars(); + this._setClippingViewport(size.w < this._display.width || + size.h < this._display.height); + } else { + this._setClippingViewport(false); + } + + // When changing clipping we might show or hide scrollbars. + // This causes the expected client dimensions to change. + if (curClip !== newClip) { + this._saveExpectedClientSize(); + } + } + + _updateScale() { + if (!this._scaleViewport) { + this._display.scale = 1.0; + } else { + const size = this._screenSize(); + this._display.autoscale(size.w, size.h); + } + this._fixScrollbars(); + } + + // Requests a change of remote desktop size. This message is an extension + // and may only be sent if we have received an ExtendedDesktopSize message + _requestRemoteResize() { + if (!this._resizeSession) { + return; + } + if (this._viewOnly) { + return; + } + if (!this._supportsSetDesktopSize) { + return; + } + + // Rate limit to one pending resize at a time + if (this._pendingRemoteResize) { + return; + } + + // And no more than once every 100ms + if ((Date.now() - this._lastResize) < 100) { + clearTimeout(this._resizeTimeout); + this._resizeTimeout = setTimeout(this._requestRemoteResize.bind(this), + 100 - (Date.now() - this._lastResize)); + return; + } + this._resizeTimeout = null; + + const size = this._screenSize(); + + // Do we actually change anything? + if (size.w === this._fbWidth && size.h === this._fbHeight) { + return; + } + + this._pendingRemoteResize = true; + this._lastResize = Date.now(); + RFB.messages.setDesktopSize(this._sock, + Math.floor(size.w), Math.floor(size.h), + this._screenID, this._screenFlags); + + Log.Debug('Requested new desktop size: ' + + size.w + 'x' + size.h); + } + + // Gets the the size of the available screen + _screenSize() { + let r = this._screen.getBoundingClientRect(); + return { w: r.width, h: r.height }; + } + + _fixScrollbars() { + // This is a hack because Safari on macOS screws up the calculation + // for when scrollbars are needed. We get scrollbars when making the + // browser smaller, despite remote resize being enabled. So to fix it + // we temporarily toggle them off and on. + const orig = this._screen.style.overflow; + this._screen.style.overflow = 'hidden'; + // Force Safari to recalculate the layout by asking for + // an element's dimensions + this._screen.getBoundingClientRect(); + this._screen.style.overflow = orig; + } + + /* + * Connection states: + * connecting + * connected + * disconnecting + * disconnected - permanent state + */ + _updateConnectionState(state) { + const oldstate = this._rfbConnectionState; + + if (state === oldstate) { + Log.Debug("Already in state '" + state + "', ignoring"); + return; + } + + // The 'disconnected' state is permanent for each RFB object + if (oldstate === 'disconnected') { + Log.Error("Tried changing state of a disconnected RFB object"); + return; + } + + // Ensure proper transitions before doing anything + switch (state) { + case 'connected': + if (oldstate !== 'connecting') { + Log.Error("Bad transition to connected state, " + + "previous connection state: " + oldstate); + return; + } + break; + + case 'disconnected': + if (oldstate !== 'disconnecting') { + Log.Error("Bad transition to disconnected state, " + + "previous connection state: " + oldstate); + return; + } + break; + + case 'connecting': + if (oldstate !== '') { + Log.Error("Bad transition to connecting state, " + + "previous connection state: " + oldstate); + return; + } + break; + + case 'disconnecting': + if (oldstate !== 'connected' && oldstate !== 'connecting') { + Log.Error("Bad transition to disconnecting state, " + + "previous connection state: " + oldstate); + return; + } + break; + + default: + Log.Error("Unknown connection state: " + state); + return; + } + + // State change actions + + this._rfbConnectionState = state; + + Log.Debug("New state '" + state + "', was '" + oldstate + "'."); + + if (this._disconnTimer && state !== 'disconnecting') { + Log.Debug("Clearing disconnect timer"); + clearTimeout(this._disconnTimer); + this._disconnTimer = null; + + // make sure we don't get a double event + this._sock.off('close'); + } + + switch (state) { + case 'connecting': + this._connect(); + break; + + case 'connected': + this.dispatchEvent(new CustomEvent("connect", { detail: {} })); + break; + + case 'disconnecting': + this._disconnect(); + + this._disconnTimer = setTimeout(() => { + Log.Error("Disconnection timed out."); + this._updateConnectionState('disconnected'); + }, DISCONNECT_TIMEOUT * 1000); + break; + + case 'disconnected': + this.dispatchEvent(new CustomEvent( + "disconnect", { detail: + { clean: this._rfbCleanDisconnect } })); + break; + } + } + + /* Print errors and disconnect + * + * The parameter 'details' is used for information that + * should be logged but not sent to the user interface. + */ + _fail(details) { + switch (this._rfbConnectionState) { + case 'disconnecting': + Log.Error("Failed when disconnecting: " + details); + break; + case 'connected': + Log.Error("Failed while connected: " + details); + break; + case 'connecting': + Log.Error("Failed when connecting: " + details); + break; + default: + Log.Error("RFB failure: " + details); + break; + } + this._rfbCleanDisconnect = false; //This is sent to the UI + + // Transition to disconnected without waiting for socket to close + this._updateConnectionState('disconnecting'); + this._updateConnectionState('disconnected'); + + return false; + } + + _setCapability(cap, val) { + this._capabilities[cap] = val; + this.dispatchEvent(new CustomEvent("capabilities", + { detail: { capabilities: this._capabilities } })); + } + + _handleMessage() { + if (this._sock.rQwait("message", 1)) { + Log.Warn("handleMessage called on an empty receive queue"); + return; + } + + switch (this._rfbConnectionState) { + case 'disconnected': + Log.Error("Got data while disconnected"); + break; + case 'connected': + while (true) { + if (this._flushing) { + break; + } + if (!this._normalMsg()) { + break; + } + if (this._sock.rQwait("message", 1)) { + break; + } + } + break; + case 'connecting': + while (this._rfbConnectionState === 'connecting') { + if (!this._initMsg()) { + break; + } + } + break; + default: + Log.Error("Got data while in an invalid state"); + break; + } + } + + _handleKeyEvent(keysym, code, down, numlock, capslock) { + // If remote state of capslock is known, and it doesn't match the local led state of + // the keyboard, we send a capslock keypress first to bring it into sync. + // If we just pressed CapsLock, or we toggled it remotely due to it being out of sync + // we clear the remote state so that we don't send duplicate or spurious fixes, + // since it may take some time to receive the new remote CapsLock state. + if (code == 'CapsLock' && down) { + this._remoteCapsLock = null; + } + if (this._remoteCapsLock !== null && capslock !== null && this._remoteCapsLock !== capslock && down) { + Log.Debug("Fixing remote caps lock"); + + this.sendKey(KeyTable.XK_Caps_Lock, 'CapsLock', true); + this.sendKey(KeyTable.XK_Caps_Lock, 'CapsLock', false); + // We clear the remote capsLock state when we do this to prevent issues with doing this twice + // before we receive an update of the the remote state. + this._remoteCapsLock = null; + } + + // Logic for numlock is exactly the same. + if (code == 'NumLock' && down) { + this._remoteNumLock = null; + } + if (this._remoteNumLock !== null && numlock !== null && this._remoteNumLock !== numlock && down) { + Log.Debug("Fixing remote num lock"); + this.sendKey(KeyTable.XK_Num_Lock, 'NumLock', true); + this.sendKey(KeyTable.XK_Num_Lock, 'NumLock', false); + this._remoteNumLock = null; + } + this.sendKey(keysym, code, down); + } + + static _convertButtonMask(buttons) { + /* The bits in MouseEvent.buttons property correspond + * to the following mouse buttons: + * 0: Left + * 1: Right + * 2: Middle + * 3: Back + * 4: Forward + * + * These bits needs to be converted to what they are defined as + * in the RFB protocol. + */ + + const buttonMaskMap = { + 0: 1 << 0, // Left + 1: 1 << 2, // Right + 2: 1 << 1, // Middle + 3: 1 << 7, // Back + 4: 1 << 8, // Forward + }; + + let bmask = 0; + for (let i = 0; i < 5; i++) { + if (buttons & (1 << i)) { + bmask |= buttonMaskMap[i]; + } + } + return bmask; + } + + _handleMouse(ev) { + /* + * We don't check connection status or viewOnly here as the + * mouse events might be used to control the viewport + */ + + if (ev.type === 'click') { + /* + * Note: This is only needed for the 'click' event as it fails + * to fire properly for the target element so we have + * to listen on the document element instead. + */ + if (ev.target !== this._canvas) { + return; + } + } + + // FIXME: if we're in view-only and not dragging, + // should we stop events? + ev.stopPropagation(); + ev.preventDefault(); + + if ((ev.type === 'click') || (ev.type === 'contextmenu')) { + return; + } + + let pos = clientToElement(ev.clientX, ev.clientY, + this._canvas); + + let bmask = RFB._convertButtonMask(ev.buttons); + + let down = ev.type == 'mousedown'; + switch (ev.type) { + case 'mousedown': + case 'mouseup': + if (this.dragViewport) { + if (down && !this._viewportDragging) { + this._viewportDragging = true; + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + this._viewportHasMoved = false; + + this._flushMouseMoveTimer(pos.x, pos.y); + + // Skip sending mouse events, instead save the current + // mouse mask so we can send it later. + this._mouseButtonMask = bmask; + break; + } else { + this._viewportDragging = false; + + // If we actually performed a drag then we are done + // here and should not send any mouse events + if (this._viewportHasMoved) { + this._mouseButtonMask = bmask; + break; + } + // Otherwise we treat this as a mouse click event. + // Send the previously saved button mask, followed + // by the current button mask at the end of this + // function. + this._sendMouse(pos.x, pos.y, this._mouseButtonMask); + } + } + if (down) { + setCapture(this._canvas); + } + this._handleMouseButton(pos.x, pos.y, bmask); + break; + case 'mousemove': + if (this._viewportDragging) { + const deltaX = this._viewportDragPos.x - pos.x; + const deltaY = this._viewportDragPos.y - pos.y; + + if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold || + Math.abs(deltaY) > dragThreshold)) { + this._viewportHasMoved = true; + + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + this._display.viewportChangePos(deltaX, deltaY); + } + + // Skip sending mouse events + break; + } + this._handleMouseMove(pos.x, pos.y); + break; + } + } + + _handleMouseButton(x, y, bmask) { + // Flush waiting move event first + this._flushMouseMoveTimer(x, y); + + this._mouseButtonMask = bmask; + this._sendMouse(x, y, this._mouseButtonMask); + } + + _handleMouseMove(x, y) { + this._mousePos = { 'x': x, 'y': y }; + + // Limit many mouse move events to one every MOUSE_MOVE_DELAY ms + if (this._mouseMoveTimer == null) { + + const timeSinceLastMove = Date.now() - this._mouseLastMoveTime; + if (timeSinceLastMove > MOUSE_MOVE_DELAY) { + this._sendMouse(x, y, this._mouseButtonMask); + this._mouseLastMoveTime = Date.now(); + } else { + // Too soon since the latest move, wait the remaining time + this._mouseMoveTimer = setTimeout(() => { + this._handleDelayedMouseMove(); + }, MOUSE_MOVE_DELAY - timeSinceLastMove); + } + } + } + + _handleDelayedMouseMove() { + this._mouseMoveTimer = null; + this._sendMouse(this._mousePos.x, this._mousePos.y, + this._mouseButtonMask); + this._mouseLastMoveTime = Date.now(); + } + + _sendMouse(x, y, mask) { + if (this._rfbConnectionState !== 'connected') { return; } + if (this._viewOnly) { return; } // View only, skip mouse events + + // Highest bit in mask is never sent to the server + if (mask & 0x8000) { + throw new Error("Illegal mouse button mask (mask: " + mask + ")"); + } + + let extendedMouseButtons = mask & 0x7f80; + + if (this._extendedPointerEventSupported && extendedMouseButtons) { + RFB.messages.extendedPointerEvent(this._sock, this._display.absX(x), + this._display.absY(y), mask); + } else { + RFB.messages.pointerEvent(this._sock, this._display.absX(x), + this._display.absY(y), mask); + } + } + + _handleWheel(ev) { + if (this._rfbConnectionState !== 'connected') { return; } + if (this._viewOnly) { return; } // View only, skip mouse events + + ev.stopPropagation(); + ev.preventDefault(); + + let pos = clientToElement(ev.clientX, ev.clientY, + this._canvas); + + let bmask = RFB._convertButtonMask(ev.buttons); + let dX = ev.deltaX; + let dY = ev.deltaY; + + // Pixel units unless it's non-zero. + // Note that if deltamode is line or page won't matter since we aren't + // sending the mouse wheel delta to the server anyway. + // The difference between pixel and line can be important however since + // we have a threshold that can be smaller than the line height. + if (ev.deltaMode !== 0) { + dX *= WHEEL_LINE_HEIGHT; + dY *= WHEEL_LINE_HEIGHT; + } + + // Mouse wheel events are sent in steps over VNC. This means that the VNC + // protocol can't handle a wheel event with specific distance or speed. + // Therefor, if we get a lot of small mouse wheel events we combine them. + this._accumulatedWheelDeltaX += dX; + this._accumulatedWheelDeltaY += dY; + + + // Generate a mouse wheel step event when the accumulated delta + // for one of the axes is large enough. + if (Math.abs(this._accumulatedWheelDeltaX) >= WHEEL_STEP) { + if (this._accumulatedWheelDeltaX < 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 5); + this._handleMouseButton(pos.x, pos.y, bmask); + } else if (this._accumulatedWheelDeltaX > 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 6); + this._handleMouseButton(pos.x, pos.y, bmask); + } + + this._accumulatedWheelDeltaX = 0; + } + if (Math.abs(this._accumulatedWheelDeltaY) >= WHEEL_STEP) { + if (this._accumulatedWheelDeltaY < 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 3); + this._handleMouseButton(pos.x, pos.y, bmask); + } else if (this._accumulatedWheelDeltaY > 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 4); + this._handleMouseButton(pos.x, pos.y, bmask); + } + + this._accumulatedWheelDeltaY = 0; + } + } + + _fakeMouseMove(ev, elementX, elementY) { + this._handleMouseMove(elementX, elementY); + this._cursor.move(ev.detail.clientX, ev.detail.clientY); + } + + _handleTapEvent(ev, bmask) { + let pos = clientToElement(ev.detail.clientX, ev.detail.clientY, + this._canvas); + + // If the user quickly taps multiple times we assume they meant to + // hit the same spot, so slightly adjust coordinates + + if ((this._gestureLastTapTime !== null) && + ((Date.now() - this._gestureLastTapTime) < DOUBLE_TAP_TIMEOUT) && + (this._gestureFirstDoubleTapEv.detail.type === ev.detail.type)) { + let dx = this._gestureFirstDoubleTapEv.detail.clientX - ev.detail.clientX; + let dy = this._gestureFirstDoubleTapEv.detail.clientY - ev.detail.clientY; + let distance = Math.hypot(dx, dy); + + if (distance < DOUBLE_TAP_THRESHOLD) { + pos = clientToElement(this._gestureFirstDoubleTapEv.detail.clientX, + this._gestureFirstDoubleTapEv.detail.clientY, + this._canvas); + } else { + this._gestureFirstDoubleTapEv = ev; + } + } else { + this._gestureFirstDoubleTapEv = ev; + } + this._gestureLastTapTime = Date.now(); + + this._fakeMouseMove(this._gestureFirstDoubleTapEv, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, bmask); + this._handleMouseButton(pos.x, pos.y, 0x0); + } + + _handleGesture(ev) { + let magnitude; + + let pos = clientToElement(ev.detail.clientX, ev.detail.clientY, + this._canvas); + switch (ev.type) { + case 'gesturestart': + switch (ev.detail.type) { + case 'onetap': + this._handleTapEvent(ev, 0x1); + break; + case 'twotap': + this._handleTapEvent(ev, 0x4); + break; + case 'threetap': + this._handleTapEvent(ev, 0x2); + break; + case 'drag': + if (this.dragViewport) { + this._viewportHasMoved = false; + this._viewportDragging = true; + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x1); + } + break; + case 'longpress': + if (this.dragViewport) { + // If dragViewport is true, we need to wait to see + // if we have dragged outside the threshold before + // sending any events to the server. + this._viewportHasMoved = false; + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x4); + } + break; + case 'twodrag': + this._gestureLastMagnitudeX = ev.detail.magnitudeX; + this._gestureLastMagnitudeY = ev.detail.magnitudeY; + this._fakeMouseMove(ev, pos.x, pos.y); + break; + case 'pinch': + this._gestureLastMagnitudeX = Math.hypot(ev.detail.magnitudeX, + ev.detail.magnitudeY); + this._fakeMouseMove(ev, pos.x, pos.y); + break; + } + break; + + case 'gesturemove': + switch (ev.detail.type) { + case 'onetap': + case 'twotap': + case 'threetap': + break; + case 'drag': + case 'longpress': + if (this.dragViewport) { + this._viewportDragging = true; + const deltaX = this._viewportDragPos.x - pos.x; + const deltaY = this._viewportDragPos.y - pos.y; + + if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold || + Math.abs(deltaY) > dragThreshold)) { + this._viewportHasMoved = true; + + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + this._display.viewportChangePos(deltaX, deltaY); + } + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + } + break; + case 'twodrag': + // Always scroll in the same position. + // We don't know if the mouse was moved so we need to move it + // every update. + this._fakeMouseMove(ev, pos.x, pos.y); + while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) > GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x8); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeY += GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) < -GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x10); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeY -= GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) > GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x20); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX += GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) < -GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x40); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX -= GESTURE_SCRLSENS; + } + break; + case 'pinch': + // Always scroll in the same position. + // We don't know if the mouse was moved so we need to move it + // every update. + this._fakeMouseMove(ev, pos.x, pos.y); + magnitude = Math.hypot(ev.detail.magnitudeX, ev.detail.magnitudeY); + if (Math.abs(magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) { + this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); + while ((magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) { + this._handleMouseButton(pos.x, pos.y, 0x8); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX += GESTURE_ZOOMSENS; + } + while ((magnitude - this._gestureLastMagnitudeX) < -GESTURE_ZOOMSENS) { + this._handleMouseButton(pos.x, pos.y, 0x10); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX -= GESTURE_ZOOMSENS; + } + } + this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", false); + break; + } + break; + + case 'gestureend': + switch (ev.detail.type) { + case 'onetap': + case 'twotap': + case 'threetap': + case 'pinch': + case 'twodrag': + break; + case 'drag': + if (this.dragViewport) { + this._viewportDragging = false; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x0); + } + break; + case 'longpress': + if (this._viewportHasMoved) { + // We don't want to send any events if we have moved + // our viewport + break; + } + + if (this.dragViewport && !this._viewportHasMoved) { + this._fakeMouseMove(ev, pos.x, pos.y); + // If dragViewport is true, we need to wait to see + // if we have dragged outside the threshold before + // sending any events to the server. + this._handleMouseButton(pos.x, pos.y, 0x4); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._viewportDragging = false; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x0); + } + break; + } + break; + } + } + + _flushMouseMoveTimer(x, y) { + if (this._mouseMoveTimer !== null) { + clearTimeout(this._mouseMoveTimer); + this._mouseMoveTimer = null; + this._sendMouse(x, y, this._mouseButtonMask); + } + } + + // Message handlers + + _negotiateProtocolVersion() { + if (this._sock.rQwait("version", 12)) { + return false; + } + + const sversion = this._sock.rQshiftStr(12).substr(4, 7); + Log.Info("Server ProtocolVersion: " + sversion); + let isRepeater = 0; + switch (sversion) { + case "000.000": // UltraVNC repeater + isRepeater = 1; + break; + case "003.003": + case "003.006": // UltraVNC + this._rfbVersion = 3.3; + break; + case "003.007": + this._rfbVersion = 3.7; + break; + case "003.008": + case "003.889": // Apple Remote Desktop + case "004.000": // Intel AMT KVM + case "004.001": // RealVNC 4.6 + case "005.000": // RealVNC 5.3 + this._rfbVersion = 3.8; + break; + default: + return this._fail("Invalid server version " + sversion); + } + + if (isRepeater) { + let repeaterID = "ID:" + this._repeaterID; + while (repeaterID.length < 250) { + repeaterID += "\0"; + } + this._sock.sQpushString(repeaterID); + this._sock.flush(); + return true; + } + + if (this._rfbVersion > this._rfbMaxVersion) { + this._rfbVersion = this._rfbMaxVersion; + } + + const cversion = "00" + parseInt(this._rfbVersion, 10) + + ".00" + ((this._rfbVersion * 10) % 10); + this._sock.sQpushString("RFB " + cversion + "\n"); + this._sock.flush(); + Log.Debug('Sent ProtocolVersion: ' + cversion); + + this._rfbInitState = 'Security'; + } + + _isSupportedSecurityType(type) { + const clientTypes = [ + securityTypeNone, + securityTypeVNCAuth, + securityTypeRA2ne, + securityTypeTight, + securityTypeVeNCrypt, + securityTypeXVP, + securityTypeARD, + securityTypeMSLogonII, + securityTypePlain, + ]; + + return clientTypes.includes(type); + } + + _negotiateSecurity() { + if (this._rfbVersion >= 3.7) { + // Server sends supported list, client decides + const numTypes = this._sock.rQshift8(); + if (this._sock.rQwait("security type", numTypes, 1)) { return false; } + + if (numTypes === 0) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "no security types"; + this._securityStatus = 1; + return true; + } + + const types = this._sock.rQshiftBytes(numTypes); + Log.Debug("Server security types: " + types); + + // Look for a matching security type in the order that the + // server prefers + this._rfbAuthScheme = -1; + for (let type of types) { + if (this._isSupportedSecurityType(type)) { + this._rfbAuthScheme = type; + break; + } + } + + if (this._rfbAuthScheme === -1) { + return this._fail("Unsupported security types (types: " + types + ")"); + } + + this._sock.sQpush8(this._rfbAuthScheme); + this._sock.flush(); + } else { + // Server decides + if (this._sock.rQwait("security scheme", 4)) { return false; } + this._rfbAuthScheme = this._sock.rQshift32(); + + if (this._rfbAuthScheme == 0) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "authentication scheme"; + this._securityStatus = 1; + return true; + } + } + + this._rfbInitState = 'Authentication'; + Log.Debug('Authenticating using scheme: ' + this._rfbAuthScheme); + + return true; + } + + _handleSecurityReason() { + if (this._sock.rQwait("reason length", 4)) { + return false; + } + const strlen = this._sock.rQshift32(); + let reason = ""; + + if (strlen > 0) { + if (this._sock.rQwait("reason", strlen, 4)) { return false; } + reason = this._sock.rQshiftStr(strlen); + } + + if (reason !== "") { + this.dispatchEvent(new CustomEvent( + "securityfailure", + { detail: { status: this._securityStatus, + reason: reason } })); + + return this._fail("Security negotiation failed on " + + this._securityContext + + " (reason: " + reason + ")"); + } else { + this.dispatchEvent(new CustomEvent( + "securityfailure", + { detail: { status: this._securityStatus } })); + + return this._fail("Security negotiation failed on " + + this._securityContext); + } + } + + // authentication + _negotiateXvpAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined || + this._rfbCredentials.target === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password", "target"] } })); + return false; + } + + this._sock.sQpush8(this._rfbCredentials.username.length); + this._sock.sQpush8(this._rfbCredentials.target.length); + this._sock.sQpushString(this._rfbCredentials.username); + this._sock.sQpushString(this._rfbCredentials.target); + + this._sock.flush(); + + this._rfbAuthScheme = securityTypeVNCAuth; + + return this._negotiateAuthentication(); + } + + // VeNCrypt authentication, currently only supports version 0.2 and only Plain subtype + _negotiateVeNCryptAuth() { + + // waiting for VeNCrypt version + if (this._rfbVeNCryptState == 0) { + if (this._sock.rQwait("vencrypt version", 2)) { return false; } + + const major = this._sock.rQshift8(); + const minor = this._sock.rQshift8(); + + if (!(major == 0 && minor == 2)) { + return this._fail("Unsupported VeNCrypt version " + major + "." + minor); + } + + this._sock.sQpush8(0); + this._sock.sQpush8(2); + this._sock.flush(); + this._rfbVeNCryptState = 1; + } + + // waiting for ACK + if (this._rfbVeNCryptState == 1) { + if (this._sock.rQwait("vencrypt ack", 1)) { return false; } + + const res = this._sock.rQshift8(); + + if (res != 0) { + return this._fail("VeNCrypt failure " + res); + } + + this._rfbVeNCryptState = 2; + } + // must fall through here (i.e. no "else if"), beacause we may have already received + // the subtypes length and won't be called again + + if (this._rfbVeNCryptState == 2) { // waiting for subtypes length + if (this._sock.rQwait("vencrypt subtypes length", 1)) { return false; } + + const subtypesLength = this._sock.rQshift8(); + if (subtypesLength < 1) { + return this._fail("VeNCrypt subtypes empty"); + } + + this._rfbVeNCryptSubtypesLength = subtypesLength; + this._rfbVeNCryptState = 3; + } + + // waiting for subtypes list + if (this._rfbVeNCryptState == 3) { + if (this._sock.rQwait("vencrypt subtypes", 4 * this._rfbVeNCryptSubtypesLength)) { return false; } + + const subtypes = []; + for (let i = 0; i < this._rfbVeNCryptSubtypesLength; i++) { + subtypes.push(this._sock.rQshift32()); + } + + // Look for a matching security type in the order that the + // server prefers + this._rfbAuthScheme = -1; + for (let type of subtypes) { + // Avoid getting in to a loop + if (type === securityTypeVeNCrypt) { + continue; + } + + if (this._isSupportedSecurityType(type)) { + this._rfbAuthScheme = type; + break; + } + } + + if (this._rfbAuthScheme === -1) { + return this._fail("Unsupported security types (types: " + subtypes + ")"); + } + + this._sock.sQpush32(this._rfbAuthScheme); + this._sock.flush(); + + this._rfbVeNCryptState = 4; + return true; + } + } + + _negotiatePlainAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + const user = encodeUTF8(this._rfbCredentials.username); + const pass = encodeUTF8(this._rfbCredentials.password); + + this._sock.sQpush32(user.length); + this._sock.sQpush32(pass.length); + this._sock.sQpushString(user); + this._sock.sQpushString(pass); + this._sock.flush(); + + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateStdVNCAuth() { + if (this._sock.rQwait("auth challenge", 16)) { return false; } + + if (this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["password"] } })); + return false; + } + + // TODO(directxman12): make genDES not require an Array + const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16)); + const response = RFB.genDES(this._rfbCredentials.password, challenge); + this._sock.sQpushBytes(response); + this._sock.flush(); + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateARDAuth() { + + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + if (this._rfbCredentials.ardPublicKey != undefined && + this._rfbCredentials.ardCredentials != undefined) { + // if the async web crypto is done return the results + this._sock.sQpushBytes(this._rfbCredentials.ardCredentials); + this._sock.sQpushBytes(this._rfbCredentials.ardPublicKey); + this._sock.flush(); + this._rfbCredentials.ardCredentials = null; + this._rfbCredentials.ardPublicKey = null; + this._rfbInitState = "SecurityResult"; + return true; + } + + if (this._sock.rQwait("read ard", 4)) { return false; } + + let generator = this._sock.rQshiftBytes(2); // DH base generator value + + let keyLength = this._sock.rQshift16(); + + if (this._sock.rQwait("read ard keylength", keyLength*2, 4)) { return false; } + + // read the server values + let prime = this._sock.rQshiftBytes(keyLength); // predetermined prime modulus + let serverPublicKey = this._sock.rQshiftBytes(keyLength); // other party's public key + + let clientKey = legacyCrypto.generateKey( + { name: "DH", g: generator, p: prime }, false, ["deriveBits"]); + this._negotiateARDAuthAsync(keyLength, serverPublicKey, clientKey); + + return false; + } + + async _negotiateARDAuthAsync(keyLength, serverPublicKey, clientKey) { + const clientPublicKey = legacyCrypto.exportKey("raw", clientKey.publicKey); + const sharedKey = legacyCrypto.deriveBits( + { name: "DH", public: serverPublicKey }, clientKey.privateKey, keyLength * 8); + + const username = encodeUTF8(this._rfbCredentials.username).substring(0, 63); + const password = encodeUTF8(this._rfbCredentials.password).substring(0, 63); + + const credentials = window.crypto.getRandomValues(new Uint8Array(128)); + for (let i = 0; i < username.length; i++) { + credentials[i] = username.charCodeAt(i); + } + credentials[username.length] = 0; + for (let i = 0; i < password.length; i++) { + credentials[64 + i] = password.charCodeAt(i); + } + credentials[64 + password.length] = 0; + + const key = await legacyCrypto.digest("MD5", sharedKey); + const cipher = await legacyCrypto.importKey( + "raw", key, { name: "AES-ECB" }, false, ["encrypt"]); + const encrypted = await legacyCrypto.encrypt({ name: "AES-ECB" }, cipher, credentials); + + this._rfbCredentials.ardCredentials = encrypted; + this._rfbCredentials.ardPublicKey = clientPublicKey; + + this._resumeAuthentication(); + } + + _negotiateTightUnixAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + this._sock.sQpush32(this._rfbCredentials.username.length); + this._sock.sQpush32(this._rfbCredentials.password.length); + this._sock.sQpushString(this._rfbCredentials.username); + this._sock.sQpushString(this._rfbCredentials.password); + this._sock.flush(); + + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateTightTunnels(numTunnels) { + const clientSupportedTunnelTypes = { + 0: { vendor: 'TGHT', signature: 'NOTUNNEL' } + }; + const serverSupportedTunnelTypes = {}; + // receive tunnel capabilities + for (let i = 0; i < numTunnels; i++) { + const capCode = this._sock.rQshift32(); + const capVendor = this._sock.rQshiftStr(4); + const capSignature = this._sock.rQshiftStr(8); + serverSupportedTunnelTypes[capCode] = { vendor: capVendor, signature: capSignature }; + } + + Log.Debug("Server Tight tunnel types: " + serverSupportedTunnelTypes); + + // Siemens touch panels have a VNC server that supports NOTUNNEL, + // but forgets to advertise it. Try to detect such servers by + // looking for their custom tunnel type. + if (serverSupportedTunnelTypes[1] && + (serverSupportedTunnelTypes[1].vendor === "SICR") && + (serverSupportedTunnelTypes[1].signature === "SCHANNEL")) { + Log.Debug("Detected Siemens server. Assuming NOTUNNEL support."); + serverSupportedTunnelTypes[0] = { vendor: 'TGHT', signature: 'NOTUNNEL' }; + } + + // choose the notunnel type + if (serverSupportedTunnelTypes[0]) { + if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor || + serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) { + return this._fail("Client's tunnel type had the incorrect " + + "vendor or signature"); + } + Log.Debug("Selected tunnel type: " + clientSupportedTunnelTypes[0]); + this._sock.sQpush32(0); // use NOTUNNEL + this._sock.flush(); + return false; // wait until we receive the sub auth count to continue + } else { + return this._fail("Server wanted tunnels, but doesn't support " + + "the notunnel type"); + } + } + + _negotiateTightAuth() { + if (!this._rfbTightVNC) { // first pass, do the tunnel negotiation + if (this._sock.rQwait("num tunnels", 4)) { return false; } + const numTunnels = this._sock.rQshift32(); + if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; } + + this._rfbTightVNC = true; + + if (numTunnels > 0) { + this._negotiateTightTunnels(numTunnels); + return false; // wait until we receive the sub auth to continue + } + } + + // second pass, do the sub-auth negotiation + if (this._sock.rQwait("sub auth count", 4)) { return false; } + const subAuthCount = this._sock.rQshift32(); + if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected + this._rfbInitState = 'SecurityResult'; + return true; + } + + if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; } + + const clientSupportedTypes = { + 'STDVNOAUTH__': 1, + 'STDVVNCAUTH_': 2, + 'TGHTULGNAUTH': 129 + }; + + const serverSupportedTypes = []; + + for (let i = 0; i < subAuthCount; i++) { + this._sock.rQshift32(); // capNum + const capabilities = this._sock.rQshiftStr(12); + serverSupportedTypes.push(capabilities); + } + + Log.Debug("Server Tight authentication types: " + serverSupportedTypes); + + for (let authType in clientSupportedTypes) { + if (serverSupportedTypes.indexOf(authType) != -1) { + this._sock.sQpush32(clientSupportedTypes[authType]); + this._sock.flush(); + Log.Debug("Selected authentication type: " + authType); + + switch (authType) { + case 'STDVNOAUTH__': // no auth + this._rfbInitState = 'SecurityResult'; + return true; + case 'STDVVNCAUTH_': + this._rfbAuthScheme = securityTypeVNCAuth; + return true; + case 'TGHTULGNAUTH': + this._rfbAuthScheme = securityTypeUnixLogon; + return true; + default: + return this._fail("Unsupported tiny auth scheme " + + "(scheme: " + authType + ")"); + } + } + } + + return this._fail("No supported sub-auth types!"); + } + + _handleRSAAESCredentialsRequired(event) { + this.dispatchEvent(event); + } + + _handleRSAAESServerVerification(event) { + this.dispatchEvent(event); + } + + _negotiateRA2neAuth() { + if (this._rfbRSAAESAuthenticationState === null) { + this._rfbRSAAESAuthenticationState = new RSAAESAuthenticationState(this._sock, () => this._rfbCredentials); + this._rfbRSAAESAuthenticationState.addEventListener( + "serververification", this._eventHandlers.handleRSAAESServerVerification); + this._rfbRSAAESAuthenticationState.addEventListener( + "credentialsrequired", this._eventHandlers.handleRSAAESCredentialsRequired); + } + this._rfbRSAAESAuthenticationState.checkInternalEvents(); + if (!this._rfbRSAAESAuthenticationState.hasStarted) { + this._rfbRSAAESAuthenticationState.negotiateRA2neAuthAsync() + .catch((e) => { + if (e.message !== "disconnect normally") { + this._fail(e.message); + } + }) + .then(() => { + this._rfbInitState = "SecurityResult"; + return true; + }).finally(() => { + this._rfbRSAAESAuthenticationState.removeEventListener( + "serververification", this._eventHandlers.handleRSAAESServerVerification); + this._rfbRSAAESAuthenticationState.removeEventListener( + "credentialsrequired", this._eventHandlers.handleRSAAESCredentialsRequired); + this._rfbRSAAESAuthenticationState = null; + }); + } + return false; + } + + _negotiateMSLogonIIAuth() { + if (this._sock.rQwait("mslogonii dh param", 24)) { return false; } + + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + const g = this._sock.rQshiftBytes(8); + const p = this._sock.rQshiftBytes(8); + const A = this._sock.rQshiftBytes(8); + const dhKey = legacyCrypto.generateKey({ name: "DH", g: g, p: p }, true, ["deriveBits"]); + const B = legacyCrypto.exportKey("raw", dhKey.publicKey); + const secret = legacyCrypto.deriveBits({ name: "DH", public: A }, dhKey.privateKey, 64); + + const key = legacyCrypto.importKey("raw", secret, { name: "DES-CBC" }, false, ["encrypt"]); + const username = encodeUTF8(this._rfbCredentials.username).substring(0, 255); + const password = encodeUTF8(this._rfbCredentials.password).substring(0, 63); + let usernameBytes = new Uint8Array(256); + let passwordBytes = new Uint8Array(64); + window.crypto.getRandomValues(usernameBytes); + window.crypto.getRandomValues(passwordBytes); + for (let i = 0; i < username.length; i++) { + usernameBytes[i] = username.charCodeAt(i); + } + usernameBytes[username.length] = 0; + for (let i = 0; i < password.length; i++) { + passwordBytes[i] = password.charCodeAt(i); + } + passwordBytes[password.length] = 0; + usernameBytes = legacyCrypto.encrypt({ name: "DES-CBC", iv: secret }, key, usernameBytes); + passwordBytes = legacyCrypto.encrypt({ name: "DES-CBC", iv: secret }, key, passwordBytes); + this._sock.sQpushBytes(B); + this._sock.sQpushBytes(usernameBytes); + this._sock.sQpushBytes(passwordBytes); + this._sock.flush(); + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateAuthentication() { + switch (this._rfbAuthScheme) { + case securityTypeNone: + if (this._rfbVersion >= 3.8) { + this._rfbInitState = 'SecurityResult'; + } else { + this._rfbInitState = 'ClientInitialisation'; + } + return true; + + case securityTypeXVP: + return this._negotiateXvpAuth(); + + case securityTypeARD: + return this._negotiateARDAuth(); + + case securityTypeVNCAuth: + return this._negotiateStdVNCAuth(); + + case securityTypeTight: + return this._negotiateTightAuth(); + + case securityTypeVeNCrypt: + return this._negotiateVeNCryptAuth(); + + case securityTypePlain: + return this._negotiatePlainAuth(); + + case securityTypeUnixLogon: + return this._negotiateTightUnixAuth(); + + case securityTypeRA2ne: + return this._negotiateRA2neAuth(); + + case securityTypeMSLogonII: + return this._negotiateMSLogonIIAuth(); + + default: + return this._fail("Unsupported auth scheme (scheme: " + + this._rfbAuthScheme + ")"); + } + } + + _handleSecurityResult() { + if (this._sock.rQwait('VNC auth response ', 4)) { return false; } + + const status = this._sock.rQshift32(); + + if (status === 0) { // OK + this._rfbInitState = 'ClientInitialisation'; + Log.Debug('Authentication OK'); + return true; + } else { + if (this._rfbVersion >= 3.8) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "security result"; + this._securityStatus = status; + return true; + } else { + this.dispatchEvent(new CustomEvent( + "securityfailure", + { detail: { status: status } })); + + return this._fail("Security handshake failed"); + } + } + } + + _negotiateServerInit() { + if (this._sock.rQwait("server initialization", 24)) { return false; } + + /* Screen size */ + const width = this._sock.rQshift16(); + const height = this._sock.rQshift16(); + + /* PIXEL_FORMAT */ + const bpp = this._sock.rQshift8(); + const depth = this._sock.rQshift8(); + const bigEndian = this._sock.rQshift8(); + const trueColor = this._sock.rQshift8(); + + const redMax = this._sock.rQshift16(); + const greenMax = this._sock.rQshift16(); + const blueMax = this._sock.rQshift16(); + const redShift = this._sock.rQshift8(); + const greenShift = this._sock.rQshift8(); + const blueShift = this._sock.rQshift8(); + this._sock.rQskipBytes(3); // padding + + // NB(directxman12): we don't want to call any callbacks or print messages until + // *after* we're past the point where we could backtrack + + /* Connection name/title */ + const nameLength = this._sock.rQshift32(); + if (this._sock.rQwait('server init name', nameLength, 24)) { return false; } + let name = this._sock.rQshiftStr(nameLength); + name = decodeUTF8(name, true); + + if (this._rfbTightVNC) { + if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + nameLength)) { return false; } + // In TightVNC mode, ServerInit message is extended + const numServerMessages = this._sock.rQshift16(); + const numClientMessages = this._sock.rQshift16(); + const numEncodings = this._sock.rQshift16(); + this._sock.rQskipBytes(2); // padding + + const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16; + if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + nameLength)) { return false; } + + // we don't actually do anything with the capability information that TIGHT sends, + // so we just skip the all of this. + + // TIGHT server message capabilities + this._sock.rQskipBytes(16 * numServerMessages); + + // TIGHT client message capabilities + this._sock.rQskipBytes(16 * numClientMessages); + + // TIGHT encoding capabilities + this._sock.rQskipBytes(16 * numEncodings); + } + + // NB(directxman12): these are down here so that we don't run them multiple times + // if we backtrack + Log.Info("Screen: " + width + "x" + height + + ", bpp: " + bpp + ", depth: " + depth + + ", bigEndian: " + bigEndian + + ", trueColor: " + trueColor + + ", redMax: " + redMax + + ", greenMax: " + greenMax + + ", blueMax: " + blueMax + + ", redShift: " + redShift + + ", greenShift: " + greenShift + + ", blueShift: " + blueShift); + + // we're past the point where we could backtrack, so it's safe to call this + this._setDesktopName(name); + this._resize(width, height); + + if (!this._viewOnly) { this._keyboard.grab(); } + + this._fbDepth = 24; + + if (this._fbName === "Intel(r) AMT KVM") { + Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode."); + this._fbDepth = 8; + } + + RFB.messages.pixelFormat(this._sock, this._fbDepth, true); + this._sendEncodings(); + RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fbWidth, this._fbHeight); + + this._updateConnectionState('connected'); + return true; + } + + _sendEncodings() { + const encs = []; + + // In preference order + encs.push(encodings.encodingCopyRect); + // Only supported with full depth support + if (this._fbDepth == 24) { + if (supportsWebCodecsH264Decode) { + encs.push(encodings.encodingH264); + } + encs.push(encodings.encodingTight); + encs.push(encodings.encodingTightPNG); + encs.push(encodings.encodingZRLE); + encs.push(encodings.encodingJPEG); + encs.push(encodings.encodingHextile); + encs.push(encodings.encodingRRE); + encs.push(encodings.encodingZlib); + } + encs.push(encodings.encodingRaw); + + // Psuedo-encoding settings + encs.push(encodings.pseudoEncodingQualityLevel0 + this._qualityLevel); + encs.push(encodings.pseudoEncodingCompressLevel0 + this._compressionLevel); + + encs.push(encodings.pseudoEncodingDesktopSize); + encs.push(encodings.pseudoEncodingLastRect); + encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent); + encs.push(encodings.pseudoEncodingQEMULedEvent); + encs.push(encodings.pseudoEncodingExtendedDesktopSize); + encs.push(encodings.pseudoEncodingXvp); + encs.push(encodings.pseudoEncodingFence); + encs.push(encodings.pseudoEncodingContinuousUpdates); + encs.push(encodings.pseudoEncodingDesktopName); + encs.push(encodings.pseudoEncodingExtendedClipboard); + encs.push(encodings.pseudoEncodingExtendedMouseButtons); + + if (this._fbDepth == 24) { + encs.push(encodings.pseudoEncodingVMwareCursor); + encs.push(encodings.pseudoEncodingCursor); + } + + RFB.messages.clientEncodings(this._sock, encs); + } + + /* RFB protocol initialization states: + * ProtocolVersion + * Security + * Authentication + * SecurityResult + * ClientInitialization - not triggered by server message + * ServerInitialization + */ + _initMsg() { + switch (this._rfbInitState) { + case 'ProtocolVersion': + return this._negotiateProtocolVersion(); + + case 'Security': + return this._negotiateSecurity(); + + case 'Authentication': + return this._negotiateAuthentication(); + + case 'SecurityResult': + return this._handleSecurityResult(); + + case 'SecurityReason': + return this._handleSecurityReason(); + + case 'ClientInitialisation': + this._sock.sQpush8(this._shared ? 1 : 0); // ClientInitialisation + this._sock.flush(); + this._rfbInitState = 'ServerInitialisation'; + return true; + + case 'ServerInitialisation': + return this._negotiateServerInit(); + + default: + return this._fail("Unknown init state (state: " + + this._rfbInitState + ")"); + } + } + + // Resume authentication handshake after it was paused for some + // reason, e.g. waiting for a password from the user + _resumeAuthentication() { + // We use setTimeout() so it's run in its own context, just like + // it originally did via the WebSocket's event handler + setTimeout(this._initMsg.bind(this), 0); + } + + _handleSetColourMapMsg() { + Log.Debug("SetColorMapEntries"); + + return this._fail("Unexpected SetColorMapEntries message"); + } + + _handleServerCutText() { + Log.Debug("ServerCutText"); + + if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; } + + this._sock.rQskipBytes(3); // Padding + + let length = this._sock.rQshift32(); + length = toSigned32bit(length); + + if (this._sock.rQwait("ServerCutText content", Math.abs(length), 8)) { return false; } + + if (length >= 0) { + //Standard msg + const text = this._sock.rQshiftStr(length); + if (this._viewOnly) { + return true; + } + + this.dispatchEvent(new CustomEvent( + "clipboard", + { detail: { text: text } })); + + } else { + //Extended msg. + length = Math.abs(length); + const flags = this._sock.rQshift32(); + let formats = flags & 0x0000FFFF; + let actions = flags & 0xFF000000; + + let isCaps = (!!(actions & extendedClipboardActionCaps)); + if (isCaps) { + this._clipboardServerCapabilitiesFormats = {}; + this._clipboardServerCapabilitiesActions = {}; + + // Update our server capabilities for Formats + for (let i = 0; i <= 15; i++) { + let index = 1 << i; + + // Check if format flag is set. + if ((formats & index)) { + this._clipboardServerCapabilitiesFormats[index] = true; + // We don't send unsolicited clipboard, so we + // ignore the size + this._sock.rQshift32(); + } + } + + // Update our server capabilities for Actions + for (let i = 24; i <= 31; i++) { + let index = 1 << i; + this._clipboardServerCapabilitiesActions[index] = !!(actions & index); + } + + /* Caps handling done, send caps with the clients + capabilities set as a response */ + let clientActions = [ + extendedClipboardActionCaps, + extendedClipboardActionRequest, + extendedClipboardActionPeek, + extendedClipboardActionNotify, + extendedClipboardActionProvide + ]; + RFB.messages.extendedClipboardCaps(this._sock, clientActions, {extendedClipboardFormatText: 0}); + + } else if (actions === extendedClipboardActionRequest) { + if (this._viewOnly) { + return true; + } + + // Check if server has told us it can handle Provide and there is clipboard data to send. + if (this._clipboardText != null && + this._clipboardServerCapabilitiesActions[extendedClipboardActionProvide]) { + + if (formats & extendedClipboardFormatText) { + RFB.messages.extendedClipboardProvide(this._sock, [extendedClipboardFormatText], [this._clipboardText]); + } + } + + } else if (actions === extendedClipboardActionPeek) { + if (this._viewOnly) { + return true; + } + + if (this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) { + + if (this._clipboardText != null) { + RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]); + } else { + RFB.messages.extendedClipboardNotify(this._sock, []); + } + } + + } else if (actions === extendedClipboardActionNotify) { + if (this._viewOnly) { + return true; + } + + if (this._clipboardServerCapabilitiesActions[extendedClipboardActionRequest]) { + + if (formats & extendedClipboardFormatText) { + RFB.messages.extendedClipboardRequest(this._sock, [extendedClipboardFormatText]); + } + } + + } else if (actions === extendedClipboardActionProvide) { + if (this._viewOnly) { + return true; + } + + if (!(formats & extendedClipboardFormatText)) { + return true; + } + // Ignore what we had in our clipboard client side. + this._clipboardText = null; + + // FIXME: Should probably verify that this data was actually requested + let zlibStream = this._sock.rQshiftBytes(length - 4); + let streamInflator = new Inflator(); + let textData = null; + + streamInflator.setInput(zlibStream); + for (let i = 0; i <= 15; i++) { + let format = 1 << i; + + if (formats & format) { + + let size = 0x00; + let sizeArray = streamInflator.inflate(4); + + size |= (sizeArray[0] << 24); + size |= (sizeArray[1] << 16); + size |= (sizeArray[2] << 8); + size |= (sizeArray[3]); + let chunk = streamInflator.inflate(size); + + if (format === extendedClipboardFormatText) { + textData = chunk; + } + } + } + streamInflator.setInput(null); + + if (textData !== null) { + let tmpText = ""; + for (let i = 0; i < textData.length; i++) { + tmpText += String.fromCharCode(textData[i]); + } + textData = tmpText; + + textData = decodeUTF8(textData); + if ((textData.length > 0) && "\0" === textData.charAt(textData.length - 1)) { + textData = textData.slice(0, -1); + } + + textData = textData.replaceAll("\r\n", "\n"); + + this.dispatchEvent(new CustomEvent( + "clipboard", + { detail: { text: textData } })); + } + } else { + return this._fail("Unexpected action in extended clipboard message: " + actions); + } + } + return true; + } + + _handleServerFenceMsg() { + if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; } + this._sock.rQskipBytes(3); // Padding + let flags = this._sock.rQshift32(); + let length = this._sock.rQshift8(); + + if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; } + + if (length > 64) { + Log.Warn("Bad payload length (" + length + ") in fence response"); + length = 64; + } + + const payload = this._sock.rQshiftStr(length); + + this._supportsFence = true; + + /* + * Fence flags + * + * (1<<0) - BlockBefore + * (1<<1) - BlockAfter + * (1<<2) - SyncNext + * (1<<31) - Request + */ + + if (!(flags & (1<<31))) { + return this._fail("Unexpected fence response"); + } + + // Filter out unsupported flags + // FIXME: support syncNext + flags &= (1<<0) | (1<<1); + + // BlockBefore and BlockAfter are automatically handled by + // the fact that we process each incoming message + // synchronuosly. + RFB.messages.clientFence(this._sock, flags, payload); + + return true; + } + + _handleXvpMsg() { + if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; } + this._sock.rQskipBytes(1); // Padding + const xvpVer = this._sock.rQshift8(); + const xvpMsg = this._sock.rQshift8(); + + switch (xvpMsg) { + case 0: // XVP_FAIL + Log.Error("XVP operation failed"); + break; + case 1: // XVP_INIT + this._rfbXvpVer = xvpVer; + Log.Info("XVP extensions enabled (version " + this._rfbXvpVer + ")"); + this._setCapability("power", true); + break; + default: + this._fail("Illegal server XVP message (msg: " + xvpMsg + ")"); + break; + } + + return true; + } + + _normalMsg() { + let msgType; + if (this._FBU.rects > 0) { + msgType = 0; + } else { + msgType = this._sock.rQshift8(); + } + + let first, ret; + switch (msgType) { + case 0: // FramebufferUpdate + ret = this._framebufferUpdate(); + if (ret && !this._enabledContinuousUpdates) { + RFB.messages.fbUpdateRequest(this._sock, true, 0, 0, + this._fbWidth, this._fbHeight); + } + return ret; + + case 1: // SetColorMapEntries + return this._handleSetColourMapMsg(); + + case 2: // Bell + Log.Debug("Bell"); + this.dispatchEvent(new CustomEvent( + "bell", + { detail: {} })); + return true; + + case 3: // ServerCutText + return this._handleServerCutText(); + + case 150: // EndOfContinuousUpdates + first = !this._supportsContinuousUpdates; + this._supportsContinuousUpdates = true; + this._enabledContinuousUpdates = false; + if (first) { + this._enabledContinuousUpdates = true; + this._updateContinuousUpdates(); + Log.Info("Enabling continuous updates."); + } else { + // FIXME: We need to send a framebufferupdaterequest here + // if we add support for turning off continuous updates + } + return true; + + case 248: // ServerFence + return this._handleServerFenceMsg(); + + case 250: // XVP + return this._handleXvpMsg(); + + default: + this._fail("Unexpected server message (type " + msgType + ")"); + Log.Debug("sock.rQpeekBytes(30): " + this._sock.rQpeekBytes(30)); + return true; + } + } + + _framebufferUpdate() { + if (this._FBU.rects === 0) { + if (this._sock.rQwait("FBU header", 3, 1)) { return false; } + this._sock.rQskipBytes(1); // Padding + this._FBU.rects = this._sock.rQshift16(); + + // Make sure the previous frame is fully rendered first + // to avoid building up an excessive queue + if (this._display.pending()) { + this._flushing = true; + this._display.flush() + .then(() => { + this._flushing = false; + // Resume processing + if (!this._sock.rQwait("message", 1)) { + this._handleMessage(); + } + }); + return false; + } + } + + while (this._FBU.rects > 0) { + if (this._FBU.encoding === null) { + if (this._sock.rQwait("rect header", 12)) { return false; } + /* New FramebufferUpdate */ + + this._FBU.x = this._sock.rQshift16(); + this._FBU.y = this._sock.rQshift16(); + this._FBU.width = this._sock.rQshift16(); + this._FBU.height = this._sock.rQshift16(); + this._FBU.encoding = this._sock.rQshift32(); + /* Encodings are signed */ + this._FBU.encoding >>= 0; + } + + if (!this._handleRect()) { + return false; + } + + this._FBU.rects--; + this._FBU.encoding = null; + } + + this._display.flip(); + + return true; // We finished this FBU + } + + _handleRect() { + switch (this._FBU.encoding) { + case encodings.pseudoEncodingLastRect: + this._FBU.rects = 1; // Will be decreased when we return + return true; + + case encodings.pseudoEncodingVMwareCursor: + return this._handleVMwareCursor(); + + case encodings.pseudoEncodingCursor: + return this._handleCursor(); + + case encodings.pseudoEncodingQEMUExtendedKeyEvent: + this._qemuExtKeyEventSupported = true; + return true; + + case encodings.pseudoEncodingDesktopName: + return this._handleDesktopName(); + + case encodings.pseudoEncodingDesktopSize: + this._resize(this._FBU.width, this._FBU.height); + return true; + + case encodings.pseudoEncodingExtendedDesktopSize: + return this._handleExtendedDesktopSize(); + + case encodings.pseudoEncodingExtendedMouseButtons: + this._extendedPointerEventSupported = true; + return true; + + case encodings.pseudoEncodingQEMULedEvent: + return this._handleLedEvent(); + + default: + return this._handleDataRect(); + } + } + + _handleVMwareCursor() { + const hotx = this._FBU.x; // hotspot-x + const hoty = this._FBU.y; // hotspot-y + const w = this._FBU.width; + const h = this._FBU.height; + if (this._sock.rQwait("VMware cursor encoding", 1)) { + return false; + } + + const cursorType = this._sock.rQshift8(); + + this._sock.rQshift8(); //Padding + + let rgba; + const bytesPerPixel = 4; + + //Classic cursor + if (cursorType == 0) { + //Used to filter away unimportant bits. + //OR is used for correct conversion in js. + const PIXEL_MASK = 0xffffff00 | 0; + rgba = new Array(w * h * bytesPerPixel); + + if (this._sock.rQwait("VMware cursor classic encoding", + (w * h * bytesPerPixel) * 2, 2)) { + return false; + } + + let andMask = new Array(w * h); + for (let pixel = 0; pixel < (w * h); pixel++) { + andMask[pixel] = this._sock.rQshift32(); + } + + let xorMask = new Array(w * h); + for (let pixel = 0; pixel < (w * h); pixel++) { + xorMask[pixel] = this._sock.rQshift32(); + } + + for (let pixel = 0; pixel < (w * h); pixel++) { + if (andMask[pixel] == 0) { + //Fully opaque pixel + let bgr = xorMask[pixel]; + let r = bgr >> 8 & 0xff; + let g = bgr >> 16 & 0xff; + let b = bgr >> 24 & 0xff; + + rgba[(pixel * bytesPerPixel) ] = r; //r + rgba[(pixel * bytesPerPixel) + 1 ] = g; //g + rgba[(pixel * bytesPerPixel) + 2 ] = b; //b + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; //a + + } else if ((andMask[pixel] & PIXEL_MASK) == + PIXEL_MASK) { + //Only screen value matters, no mouse colouring + if (xorMask[pixel] == 0) { + //Transparent pixel + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0x00; + + } else if ((xorMask[pixel] & PIXEL_MASK) == + PIXEL_MASK) { + //Inverted pixel, not supported in browsers. + //Fully opaque instead. + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + + } else { + //Unhandled xorMask + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + } + + } else { + //Unhandled andMask + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + } + } + + //Alpha cursor. + } else if (cursorType == 1) { + if (this._sock.rQwait("VMware cursor alpha encoding", + (w * h * 4), 2)) { + return false; + } + + rgba = new Array(w * h * bytesPerPixel); + + for (let pixel = 0; pixel < (w * h); pixel++) { + let data = this._sock.rQshift32(); + + rgba[(pixel * 4) ] = data >> 24 & 0xff; //r + rgba[(pixel * 4) + 1 ] = data >> 16 & 0xff; //g + rgba[(pixel * 4) + 2 ] = data >> 8 & 0xff; //b + rgba[(pixel * 4) + 3 ] = data & 0xff; //a + } + + } else { + Log.Warn("The given cursor type is not supported: " + + cursorType + " given."); + return false; + } + + this._updateCursor(rgba, hotx, hoty, w, h); + + return true; + } + + _handleCursor() { + const hotx = this._FBU.x; // hotspot-x + const hoty = this._FBU.y; // hotspot-y + const w = this._FBU.width; + const h = this._FBU.height; + + const pixelslength = w * h * 4; + const masklength = Math.ceil(w / 8) * h; + + let bytes = pixelslength + masklength; + if (this._sock.rQwait("cursor encoding", bytes)) { + return false; + } + + // Decode from BGRX pixels + bit mask to RGBA + const pixels = this._sock.rQshiftBytes(pixelslength); + const mask = this._sock.rQshiftBytes(masklength); + let rgba = new Uint8Array(w * h * 4); + + let pixIdx = 0; + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + let maskIdx = y * Math.ceil(w / 8) + Math.floor(x / 8); + let alpha = (mask[maskIdx] << (x % 8)) & 0x80 ? 255 : 0; + rgba[pixIdx ] = pixels[pixIdx + 2]; + rgba[pixIdx + 1] = pixels[pixIdx + 1]; + rgba[pixIdx + 2] = pixels[pixIdx]; + rgba[pixIdx + 3] = alpha; + pixIdx += 4; + } + } + + this._updateCursor(rgba, hotx, hoty, w, h); + + return true; + } + + _handleDesktopName() { + if (this._sock.rQwait("DesktopName", 4)) { + return false; + } + + let length = this._sock.rQshift32(); + + if (this._sock.rQwait("DesktopName", length, 4)) { + return false; + } + + let name = this._sock.rQshiftStr(length); + name = decodeUTF8(name, true); + + this._setDesktopName(name); + + return true; + } + + _handleLedEvent() { + if (this._sock.rQwait("LED status", 1)) { + return false; + } + + let data = this._sock.rQshift8(); + // ScrollLock state can be retrieved with data & 1. This is currently not needed. + let numLock = data & 2 ? true : false; + let capsLock = data & 4 ? true : false; + this._remoteCapsLock = capsLock; + this._remoteNumLock = numLock; + + return true; + } + + _handleExtendedDesktopSize() { + if (this._sock.rQwait("ExtendedDesktopSize", 4)) { + return false; + } + + const numberOfScreens = this._sock.rQpeek8(); + + let bytes = 4 + (numberOfScreens * 16); + if (this._sock.rQwait("ExtendedDesktopSize", bytes)) { + return false; + } + + const firstUpdate = !this._supportsSetDesktopSize; + this._supportsSetDesktopSize = true; + + this._sock.rQskipBytes(1); // number-of-screens + this._sock.rQskipBytes(3); // padding + + for (let i = 0; i < numberOfScreens; i += 1) { + // Save the id and flags of the first screen + if (i === 0) { + this._screenID = this._sock.rQshift32(); // id + this._sock.rQskipBytes(2); // x-position + this._sock.rQskipBytes(2); // y-position + this._sock.rQskipBytes(2); // width + this._sock.rQskipBytes(2); // height + this._screenFlags = this._sock.rQshift32(); // flags + } else { + this._sock.rQskipBytes(16); + } + } + + /* + * The x-position indicates the reason for the change: + * + * 0 - server resized on its own + * 1 - this client requested the resize + * 2 - another client requested the resize + */ + + if (this._FBU.x === 1) { + this._pendingRemoteResize = false; + } + + // We need to handle errors when we requested the resize. + if (this._FBU.x === 1 && this._FBU.y !== 0) { + let msg = ""; + // The y-position indicates the status code from the server + switch (this._FBU.y) { + case 1: + msg = "Resize is administratively prohibited"; + break; + case 2: + msg = "Out of resources"; + break; + case 3: + msg = "Invalid screen layout"; + break; + default: + msg = "Unknown reason"; + break; + } + Log.Warn("Server did not accept the resize request: " + + msg); + } else { + this._resize(this._FBU.width, this._FBU.height); + } + + // Normally we only apply the current resize mode after a + // window resize event. However there is no such trigger on the + // initial connect. And we don't know if the server supports + // resizing until we've gotten here. + if (firstUpdate) { + this._requestRemoteResize(); + } + + if (this._FBU.x === 1 && this._FBU.y === 0) { + // We might have resized again whilst waiting for the + // previous request, so check if we are in sync + this._requestRemoteResize(); + } + + return true; + } + + _handleDataRect() { + let decoder = this._decoders[this._FBU.encoding]; + if (!decoder) { + this._fail("Unsupported encoding (encoding: " + + this._FBU.encoding + ")"); + return false; + } + + try { + return decoder.decodeRect(this._FBU.x, this._FBU.y, + this._FBU.width, this._FBU.height, + this._sock, this._display, + this._fbDepth); + } catch (err) { + this._fail("Error decoding rect: " + err); + return false; + } + } + + _updateContinuousUpdates() { + if (!this._enabledContinuousUpdates) { return; } + + RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0, + this._fbWidth, this._fbHeight); + } + + // Handle resize-messages from the server + _resize(width, height) { + this._fbWidth = width; + this._fbHeight = height; + + this._display.resize(this._fbWidth, this._fbHeight); + + // Adjust the visible viewport based on the new dimensions + this._updateClip(); + this._updateScale(); + + this._updateContinuousUpdates(); + + // Keep this size until browser client size changes + this._saveExpectedClientSize(); + } + + _xvpOp(ver, op) { + if (this._rfbXvpVer < ver) { return; } + Log.Info("Sending XVP operation " + op + " (version " + ver + ")"); + RFB.messages.xvpOp(this._sock, ver, op); + } + + _updateCursor(rgba, hotx, hoty, w, h) { + this._cursorImage = { + rgbaPixels: rgba, + hotx: hotx, hoty: hoty, w: w, h: h, + }; + this._refreshCursor(); + } + + _shouldShowDotCursor() { + // Called when this._cursorImage is updated + if (!this._showDotCursor) { + // User does not want to see the dot, so... + return false; + } + + // The dot should not be shown if the cursor is already visible, + // i.e. contains at least one not-fully-transparent pixel. + // So iterate through all alpha bytes in rgba and stop at the + // first non-zero. + for (let i = 3; i < this._cursorImage.rgbaPixels.length; i += 4) { + if (this._cursorImage.rgbaPixels[i]) { + return false; + } + } + + // At this point, we know that the cursor is fully transparent, and + // the user wants to see the dot instead of this. + return true; + } + + _refreshCursor() { + if (this._rfbConnectionState !== "connecting" && + this._rfbConnectionState !== "connected") { + return; + } + const image = this._shouldShowDotCursor() ? RFB.cursors.dot : this._cursorImage; + this._cursor.change(image.rgbaPixels, + image.hotx, image.hoty, + image.w, image.h + ); + } + + static genDES(password, challenge) { + const passwordChars = password.split('').map(c => c.charCodeAt(0)); + const key = legacyCrypto.importKey( + "raw", passwordChars, { name: "DES-ECB" }, false, ["encrypt"]); + return legacyCrypto.encrypt({ name: "DES-ECB" }, key, challenge); + } +} + +// Class Methods +RFB.messages = { + keyEvent(sock, keysym, down) { + sock.sQpush8(4); // msg-type + sock.sQpush8(down); + + sock.sQpush16(0); + + sock.sQpush32(keysym); + + sock.flush(); + }, + + QEMUExtendedKeyEvent(sock, keysym, down, keycode) { + function getRFBkeycode(xtScanCode) { + const upperByte = (keycode >> 8); + const lowerByte = (keycode & 0x00ff); + if (upperByte === 0xe0 && lowerByte < 0x7f) { + return lowerByte | 0x80; + } + return xtScanCode; + } + + sock.sQpush8(255); // msg-type + sock.sQpush8(0); // sub msg-type + + sock.sQpush16(down); + + sock.sQpush32(keysym); + + const RFBkeycode = getRFBkeycode(keycode); + + sock.sQpush32(RFBkeycode); + + sock.flush(); + }, + + pointerEvent(sock, x, y, mask) { + sock.sQpush8(5); // msg-type + + // Marker bit must be set to 0, otherwise the server might + // confuse the marker bit with the highest bit in a normal + // PointerEvent message. + mask = mask & 0x7f; + sock.sQpush8(mask); + + sock.sQpush16(x); + sock.sQpush16(y); + + sock.flush(); + }, + + extendedPointerEvent(sock, x, y, mask) { + sock.sQpush8(5); // msg-type + + let higherBits = (mask >> 7) & 0xff; + + // Bits 2-7 are reserved + if (higherBits & 0xfc) { + throw new Error("Invalid mouse button mask: " + mask); + } + + let lowerBits = mask & 0x7f; + lowerBits |= 0x80; // Set marker bit to 1 + + sock.sQpush8(lowerBits); + sock.sQpush16(x); + sock.sQpush16(y); + sock.sQpush8(higherBits); + + sock.flush(); + }, + + // Used to build Notify and Request data. + _buildExtendedClipboardFlags(actions, formats) { + let data = new Uint8Array(4); + let formatFlag = 0x00000000; + let actionFlag = 0x00000000; + + for (let i = 0; i < actions.length; i++) { + actionFlag |= actions[i]; + } + + for (let i = 0; i < formats.length; i++) { + formatFlag |= formats[i]; + } + + data[0] = actionFlag >> 24; // Actions + data[1] = 0x00; // Reserved + data[2] = 0x00; // Reserved + data[3] = formatFlag; // Formats + + return data; + }, + + extendedClipboardProvide(sock, formats, inData) { + // Deflate incomming data and their sizes + let deflator = new Deflator(); + let dataToDeflate = []; + + for (let i = 0; i < formats.length; i++) { + // We only support the format Text at this time + if (formats[i] != extendedClipboardFormatText) { + throw new Error("Unsupported extended clipboard format for Provide message."); + } + + // Change lone \r or \n into \r\n as defined in rfbproto + inData[i] = inData[i].replace(/\r\n|\r|\n/gm, "\r\n"); + + // Check if it already has \0 + let text = encodeUTF8(inData[i] + "\0"); + + dataToDeflate.push( (text.length >> 24) & 0xFF, + (text.length >> 16) & 0xFF, + (text.length >> 8) & 0xFF, + (text.length & 0xFF)); + + for (let j = 0; j < text.length; j++) { + dataToDeflate.push(text.charCodeAt(j)); + } + } + + let deflatedData = deflator.deflate(new Uint8Array(dataToDeflate)); + + // Build data to send + let data = new Uint8Array(4 + deflatedData.length); + data.set(RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionProvide], + formats)); + data.set(deflatedData, 4); + + RFB.messages.clientCutText(sock, data, true); + }, + + extendedClipboardNotify(sock, formats) { + let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionNotify], + formats); + RFB.messages.clientCutText(sock, flags, true); + }, + + extendedClipboardRequest(sock, formats) { + let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionRequest], + formats); + RFB.messages.clientCutText(sock, flags, true); + }, + + extendedClipboardCaps(sock, actions, formats) { + let formatKeys = Object.keys(formats); + let data = new Uint8Array(4 + (4 * formatKeys.length)); + + formatKeys.map(x => parseInt(x)); + formatKeys.sort((a, b) => a - b); + + data.set(RFB.messages._buildExtendedClipboardFlags(actions, [])); + + let loopOffset = 4; + for (let i = 0; i < formatKeys.length; i++) { + data[loopOffset] = formats[formatKeys[i]] >> 24; + data[loopOffset + 1] = formats[formatKeys[i]] >> 16; + data[loopOffset + 2] = formats[formatKeys[i]] >> 8; + data[loopOffset + 3] = formats[formatKeys[i]] >> 0; + + loopOffset += 4; + data[3] |= (1 << formatKeys[i]); // Update our format flags + } + + RFB.messages.clientCutText(sock, data, true); + }, + + clientCutText(sock, data, extended = false) { + sock.sQpush8(6); // msg-type + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + let length; + if (extended) { + length = toUnsigned32bit(-data.length); + } else { + length = data.length; + } + + sock.sQpush32(length); + sock.sQpushBytes(data); + sock.flush(); + }, + + setDesktopSize(sock, width, height, id, flags) { + sock.sQpush8(251); // msg-type + + sock.sQpush8(0); // padding + + sock.sQpush16(width); + sock.sQpush16(height); + + sock.sQpush8(1); // number-of-screens + + sock.sQpush8(0); // padding + + // screen array + sock.sQpush32(id); + sock.sQpush16(0); // x-position + sock.sQpush16(0); // y-position + sock.sQpush16(width); + sock.sQpush16(height); + sock.sQpush32(flags); + + sock.flush(); + }, + + clientFence(sock, flags, payload) { + sock.sQpush8(248); // msg-type + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + sock.sQpush32(flags); + + sock.sQpush8(payload.length); + sock.sQpushString(payload); + + sock.flush(); + }, + + enableContinuousUpdates(sock, enable, x, y, width, height) { + sock.sQpush8(150); // msg-type + + sock.sQpush8(enable); + + sock.sQpush16(x); + sock.sQpush16(y); + sock.sQpush16(width); + sock.sQpush16(height); + + sock.flush(); + }, + + pixelFormat(sock, depth, trueColor) { + let bpp; + + if (depth > 16) { + bpp = 32; + } else if (depth > 8) { + bpp = 16; + } else { + bpp = 8; + } + + const bits = Math.floor(depth/3); + + sock.sQpush8(0); // msg-type + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + sock.sQpush8(bpp); + sock.sQpush8(depth); + sock.sQpush8(0); // little-endian + sock.sQpush8(trueColor ? 1 : 0); + + sock.sQpush16((1 << bits) - 1); // red-max + sock.sQpush16((1 << bits) - 1); // green-max + sock.sQpush16((1 << bits) - 1); // blue-max + + sock.sQpush8(bits * 0); // red-shift + sock.sQpush8(bits * 1); // green-shift + sock.sQpush8(bits * 2); // blue-shift + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + sock.flush(); + }, + + clientEncodings(sock, encodings) { + sock.sQpush8(2); // msg-type + + sock.sQpush8(0); // padding + + sock.sQpush16(encodings.length); + for (let i = 0; i < encodings.length; i++) { + sock.sQpush32(encodings[i]); + } + + sock.flush(); + }, + + fbUpdateRequest(sock, incremental, x, y, w, h) { + if (typeof(x) === "undefined") { x = 0; } + if (typeof(y) === "undefined") { y = 0; } + + sock.sQpush8(3); // msg-type + + sock.sQpush8(incremental ? 1 : 0); + + sock.sQpush16(x); + sock.sQpush16(y); + sock.sQpush16(w); + sock.sQpush16(h); + + sock.flush(); + }, + + xvpOp(sock, ver, op) { + sock.sQpush8(250); // msg-type + + sock.sQpush8(0); // padding + + sock.sQpush8(ver); + sock.sQpush8(op); + + sock.flush(); + } +}; + +RFB.cursors = { + none: { + rgbaPixels: new Uint8Array(), + w: 0, h: 0, + hotx: 0, hoty: 0, + }, + + dot: { + /* eslint-disable indent */ + rgbaPixels: new Uint8Array([ + 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, + 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 255, + 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, + ]), + /* eslint-enable indent */ + w: 3, h: 3, + hotx: 1, hoty: 1, + } +}; diff --git a/engine/static/vendor/novnc/core/util/browser.js b/engine/static/vendor/novnc/core/util/browser.js new file mode 100644 index 00000000..63596d21 --- /dev/null +++ b/engine/static/vendor/novnc/core/util/browser.js @@ -0,0 +1,233 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + * Browser feature support detection + */ + +import * as Log from './logging.js'; +import Base64 from '../base64.js'; + +// Touch detection +export let isTouchDevice = ('ontouchstart' in document.documentElement) || + // required for Chrome debugger + (document.ontouchstart !== undefined) || + // required for MS Surface + (navigator.maxTouchPoints > 0) || + (navigator.msMaxTouchPoints > 0); +window.addEventListener('touchstart', function onFirstTouch() { + isTouchDevice = true; + window.removeEventListener('touchstart', onFirstTouch, false); +}, false); + + +// The goal is to find a certain physical width, the devicePixelRatio +// brings us a bit closer but is not optimal. +export let dragThreshold = 10 * (window.devicePixelRatio || 1); + +let _supportsCursorURIs = false; + +try { + const target = document.createElement('canvas'); + target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default'; + + if (target.style.cursor.indexOf("url") === 0) { + Log.Info("Data URI scheme cursor supported"); + _supportsCursorURIs = true; + } else { + Log.Warn("Data URI scheme cursor not supported"); + } +} catch (exc) { + Log.Error("Data URI scheme cursor test exception: " + exc); +} + +export const supportsCursorURIs = _supportsCursorURIs; + +let _hasScrollbarGutter = true; +try { + // Create invisible container + const container = document.createElement('div'); + container.style.visibility = 'hidden'; + container.style.overflow = 'scroll'; // forcing scrollbars + document.body.appendChild(container); + + // Create a div and place it in the container + const child = document.createElement('div'); + container.appendChild(child); + + // Calculate the difference between the container's full width + // and the child's width - the difference is the scrollbars + const scrollbarWidth = (container.offsetWidth - child.offsetWidth); + + // Clean up + container.parentNode.removeChild(container); + + _hasScrollbarGutter = scrollbarWidth != 0; +} catch (exc) { + Log.Error("Scrollbar test exception: " + exc); +} +export const hasScrollbarGutter = _hasScrollbarGutter; + +export let supportsWebCodecsH264Decode = false; + +async function _checkWebCodecsH264DecodeSupport() { + if (!('VideoDecoder' in window)) { + return false; + } + + // We'll need to make do with some placeholders here + const config = { + codec: 'avc1.42401f', + codedWidth: 1920, + codedHeight: 1080, + optimizeForLatency: true, + }; + + let support = await VideoDecoder.isConfigSupported(config); + if (!support.supported) { + return false; + } + + // Firefox incorrectly reports supports for H.264 under some + // circumstances, so we need to actually test a real frame + // https://bugzilla.mozilla.org/show_bug.cgi?id=1932392 + + const data = new Uint8Array(Base64.decode( + 'AAAAAWdCwBTZnpuAgICgAAADACAAAAZB4oVNAAAAAWjJYyyAAAABBgX//4Hc' + + 'Rem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY0IHIzMTA4IDMxZTE5Zjkg' + + 'LSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDIz' + + 'IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9u' + + 'czogY2FiYWM9MCByZWY9NSBkZWJsb2NrPTE6MDowIGFuYWx5c2U9MHgxOjB4' + + 'MTExIG1lPWhleCBzdWJtZT04IHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4' + + 'ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0yIDh4' + + 'OGRjdD0wIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJv' + + 'bWFfcXBfb2Zmc2V0PS0yIHRocmVhZHM9MSBsb29rYWhlYWRfdGhyZWFkcz0x' + + 'IHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9' + + 'MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVz' + + 'PTAgd2VpZ2h0cD0wIGtleWludD1pbmZpbml0ZSBrZXlpbnRfbWluPTI1IHNj' + + 'ZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NTAgcmM9' + + 'YWJyIG1idHJlZT0xIGJpdHJhdGU9NDAwIHJhdGV0b2w9MS4wIHFjb21wPTAu' + + 'NjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFx' + + 'PTE6MS4wMACAAAABZYiEBrxmKAAPVccAAS044AA5DRJMnkycJk4TPw==')); + + let gotframe = false; + let error = null; + + let decoder = new VideoDecoder({ + output: (frame) => { gotframe = true; frame.close(); }, + error: (e) => { error = e; }, + }); + let chunk = new EncodedVideoChunk({ + timestamp: 0, + type: 'key', + data: data, + }); + + decoder.configure(config); + decoder.decode(chunk); + try { + await decoder.flush(); + } catch (e) { + // Firefox incorrectly throws an exception here + // https://bugzilla.mozilla.org/show_bug.cgi?id=1932566 + error = e; + } + + // Firefox fails to deliver the error on Windows, so we need to + // check if we got a frame instead + // https://bugzilla.mozilla.org/show_bug.cgi?id=1932579 + if (!gotframe) { + return false; + } + + if (error !== null) { + return false; + } + + return true; +} +supportsWebCodecsH264Decode = await _checkWebCodecsH264DecodeSupport(); + +/* + * The functions for detection of platforms and browsers below are exported + * but the use of these should be minimized as much as possible. + * + * It's better to use feature detection than platform detection. + */ + +/* OS */ + +export function isMac() { + return !!(/mac/i).exec(navigator.platform); +} + +export function isWindows() { + return !!(/win/i).exec(navigator.platform); +} + +export function isIOS() { + return (!!(/ipad/i).exec(navigator.platform) || + !!(/iphone/i).exec(navigator.platform) || + !!(/ipod/i).exec(navigator.platform)); +} + +export function isAndroid() { + /* Android sets navigator.platform to Linux :/ */ + return !!navigator.userAgent.match('Android '); +} + +export function isChromeOS() { + /* ChromeOS sets navigator.platform to Linux :/ */ + return !!navigator.userAgent.match(' CrOS '); +} + +/* Browser */ + +export function isSafari() { + return !!navigator.userAgent.match('Safari/...') && + !navigator.userAgent.match('Chrome/...') && + !navigator.userAgent.match('Chromium/...') && + !navigator.userAgent.match('Epiphany/...'); +} + +export function isFirefox() { + return !!navigator.userAgent.match('Firefox/...') && + !navigator.userAgent.match('Seamonkey/...'); +} + +export function isChrome() { + return !!navigator.userAgent.match('Chrome/...') && + !navigator.userAgent.match('Chromium/...') && + !navigator.userAgent.match('Edg/...') && + !navigator.userAgent.match('OPR/...'); +} + +export function isChromium() { + return !!navigator.userAgent.match('Chromium/...'); +} + +export function isOpera() { + return !!navigator.userAgent.match('OPR/...'); +} + +export function isEdge() { + return !!navigator.userAgent.match('Edg/...'); +} + +/* Engine */ + +export function isGecko() { + return !!navigator.userAgent.match('Gecko/...'); +} + +export function isWebKit() { + return !!navigator.userAgent.match('AppleWebKit/...') && + !navigator.userAgent.match('Chrome/...'); +} + +export function isBlink() { + return !!navigator.userAgent.match('Chrome/...'); +} diff --git a/engine/static/vendor/novnc/core/util/cursor.js b/engine/static/vendor/novnc/core/util/cursor.js new file mode 100644 index 00000000..6d689e7d --- /dev/null +++ b/engine/static/vendor/novnc/core/util/cursor.js @@ -0,0 +1,249 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +import { supportsCursorURIs, isTouchDevice } from './browser.js'; + +const useFallback = !supportsCursorURIs || isTouchDevice; + +export default class Cursor { + constructor() { + this._target = null; + + this._canvas = document.createElement('canvas'); + + if (useFallback) { + this._canvas.style.position = 'fixed'; + this._canvas.style.zIndex = '65535'; + this._canvas.style.pointerEvents = 'none'; + // Safari on iOS can select the cursor image + // https://bugs.webkit.org/show_bug.cgi?id=249223 + this._canvas.style.userSelect = 'none'; + this._canvas.style.WebkitUserSelect = 'none'; + // Can't use "display" because of Firefox bug #1445997 + this._canvas.style.visibility = 'hidden'; + } + + this._position = { x: 0, y: 0 }; + this._hotSpot = { x: 0, y: 0 }; + + this._eventHandlers = { + 'mouseover': this._handleMouseOver.bind(this), + 'mouseleave': this._handleMouseLeave.bind(this), + 'mousemove': this._handleMouseMove.bind(this), + 'mouseup': this._handleMouseUp.bind(this), + }; + } + + attach(target) { + if (this._target) { + this.detach(); + } + + this._target = target; + + if (useFallback) { + document.body.appendChild(this._canvas); + + const options = { capture: true, passive: true }; + this._target.addEventListener('mouseover', this._eventHandlers.mouseover, options); + this._target.addEventListener('mouseleave', this._eventHandlers.mouseleave, options); + this._target.addEventListener('mousemove', this._eventHandlers.mousemove, options); + this._target.addEventListener('mouseup', this._eventHandlers.mouseup, options); + } + + this.clear(); + } + + detach() { + if (!this._target) { + return; + } + + if (useFallback) { + const options = { capture: true, passive: true }; + this._target.removeEventListener('mouseover', this._eventHandlers.mouseover, options); + this._target.removeEventListener('mouseleave', this._eventHandlers.mouseleave, options); + this._target.removeEventListener('mousemove', this._eventHandlers.mousemove, options); + this._target.removeEventListener('mouseup', this._eventHandlers.mouseup, options); + + if (document.contains(this._canvas)) { + document.body.removeChild(this._canvas); + } + } + + this._target = null; + } + + change(rgba, hotx, hoty, w, h) { + if ((w === 0) || (h === 0)) { + this.clear(); + return; + } + + this._position.x = this._position.x + this._hotSpot.x - hotx; + this._position.y = this._position.y + this._hotSpot.y - hoty; + this._hotSpot.x = hotx; + this._hotSpot.y = hoty; + + let ctx = this._canvas.getContext('2d'); + + this._canvas.width = w; + this._canvas.height = h; + + let img = new ImageData(new Uint8ClampedArray(rgba), w, h); + ctx.clearRect(0, 0, w, h); + ctx.putImageData(img, 0, 0); + + if (useFallback) { + this._updatePosition(); + } else { + let url = this._canvas.toDataURL(); + this._target.style.cursor = 'url(' + url + ')' + hotx + ' ' + hoty + ', default'; + } + } + + clear() { + this._target.style.cursor = 'none'; + this._canvas.width = 0; + this._canvas.height = 0; + this._position.x = this._position.x + this._hotSpot.x; + this._position.y = this._position.y + this._hotSpot.y; + this._hotSpot.x = 0; + this._hotSpot.y = 0; + } + + // Mouse events might be emulated, this allows + // moving the cursor in such cases + move(clientX, clientY) { + if (!useFallback) { + return; + } + // clientX/clientY are relative the _visual viewport_, + // but our position is relative the _layout viewport_, + // so try to compensate when we can + if (window.visualViewport) { + this._position.x = clientX + window.visualViewport.offsetLeft; + this._position.y = clientY + window.visualViewport.offsetTop; + } else { + this._position.x = clientX; + this._position.y = clientY; + } + this._updatePosition(); + let target = document.elementFromPoint(clientX, clientY); + this._updateVisibility(target); + } + + _handleMouseOver(event) { + // This event could be because we're entering the target, or + // moving around amongst its sub elements. Let the move handler + // sort things out. + this._handleMouseMove(event); + } + + _handleMouseLeave(event) { + // Check if we should show the cursor on the element we are leaving to + this._updateVisibility(event.relatedTarget); + } + + _handleMouseMove(event) { + this._updateVisibility(event.target); + + this._position.x = event.clientX - this._hotSpot.x; + this._position.y = event.clientY - this._hotSpot.y; + + this._updatePosition(); + } + + _handleMouseUp(event) { + // We might get this event because of a drag operation that + // moved outside of the target. Check what's under the cursor + // now and adjust visibility based on that. + let target = document.elementFromPoint(event.clientX, event.clientY); + this._updateVisibility(target); + + // Captures end with a mouseup but we can't know the event order of + // mouseup vs releaseCapture. + // + // In the cases when releaseCapture comes first, the code above is + // enough. + // + // In the cases when the mouseup comes first, we need wait for the + // browser to flush all events and then check again if the cursor + // should be visible. + if (this._captureIsActive()) { + window.setTimeout(() => { + // We might have detached at this point + if (!this._target) { + return; + } + // Refresh the target from elementFromPoint since queued events + // might have altered the DOM + target = document.elementFromPoint(event.clientX, + event.clientY); + this._updateVisibility(target); + }, 0); + } + } + + _showCursor() { + if (this._canvas.style.visibility === 'hidden') { + this._canvas.style.visibility = ''; + } + } + + _hideCursor() { + if (this._canvas.style.visibility !== 'hidden') { + this._canvas.style.visibility = 'hidden'; + } + } + + // Should we currently display the cursor? + // (i.e. are we over the target, or a child of the target without a + // different cursor set) + _shouldShowCursor(target) { + if (!target) { + return false; + } + // Easy case + if (target === this._target) { + return true; + } + // Other part of the DOM? + if (!this._target.contains(target)) { + return false; + } + // Has the child its own cursor? + // FIXME: How can we tell that a sub element has an + // explicit "cursor: none;"? + if (window.getComputedStyle(target).cursor !== 'none') { + return false; + } + return true; + } + + _updateVisibility(target) { + // When the cursor target has capture we want to show the cursor. + // So, if a capture is active - look at the captured element instead. + if (this._captureIsActive()) { + target = document.captureElement; + } + if (this._shouldShowCursor(target)) { + this._showCursor(); + } else { + this._hideCursor(); + } + } + + _updatePosition() { + this._canvas.style.left = this._position.x + "px"; + this._canvas.style.top = this._position.y + "px"; + } + + _captureIsActive() { + return document.captureElement && + document.documentElement.contains(document.captureElement); + } +} diff --git a/engine/static/vendor/novnc/core/util/element.js b/engine/static/vendor/novnc/core/util/element.js new file mode 100644 index 00000000..17d82d58 --- /dev/null +++ b/engine/static/vendor/novnc/core/util/element.js @@ -0,0 +1,32 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * HTML element utility functions + */ + +export function clientToElement(x, y, elem) { + const bounds = elem.getBoundingClientRect(); + let pos = { x: 0, y: 0 }; + // Clip to target bounds + if (x < bounds.left) { + pos.x = 0; + } else if (x >= bounds.right) { + pos.x = bounds.width - 1; + } else { + pos.x = x - bounds.left; + } + if (y < bounds.top) { + pos.y = 0; + } else if (y >= bounds.bottom) { + pos.y = bounds.height - 1; + } else { + pos.y = y - bounds.top; + } + return pos; +} diff --git a/engine/static/vendor/novnc/core/util/events.js b/engine/static/vendor/novnc/core/util/events.js new file mode 100644 index 00000000..26aa9790 --- /dev/null +++ b/engine/static/vendor/novnc/core/util/events.js @@ -0,0 +1,138 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * Cross-browser event and position routines + */ + +export function getPointerEvent(e) { + return e.changedTouches ? e.changedTouches[0] : e.touches ? e.touches[0] : e; +} + +export function stopEvent(e) { + e.stopPropagation(); + e.preventDefault(); +} + +// Emulate Element.setCapture() when not supported +let _captureRecursion = false; +let _elementForUnflushedEvents = null; +document.captureElement = null; +function _captureProxy(e) { + // Recursion protection as we'll see our own event + if (_captureRecursion) return; + + // Clone the event as we cannot dispatch an already dispatched event + const newEv = new e.constructor(e.type, e); + + _captureRecursion = true; + if (document.captureElement) { + document.captureElement.dispatchEvent(newEv); + } else { + _elementForUnflushedEvents.dispatchEvent(newEv); + } + _captureRecursion = false; + + // Avoid double events + e.stopPropagation(); + + // Respect the wishes of the redirected event handlers + if (newEv.defaultPrevented) { + e.preventDefault(); + } + + // Implicitly release the capture on button release + if (e.type === "mouseup") { + releaseCapture(); + } +} + +// Follow cursor style of target element +function _capturedElemChanged() { + const proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + proxyElem.style.cursor = window.getComputedStyle(document.captureElement).cursor; +} + +const _captureObserver = new MutationObserver(_capturedElemChanged); + +export function setCapture(target) { + if (target.setCapture) { + + target.setCapture(); + document.captureElement = target; + } else { + // Release any existing capture in case this method is + // called multiple times without coordination + releaseCapture(); + + let proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + + if (proxyElem === null) { + proxyElem = document.createElement("div"); + proxyElem.id = "noVNC_mouse_capture_elem"; + proxyElem.style.position = "fixed"; + proxyElem.style.top = "0px"; + proxyElem.style.left = "0px"; + proxyElem.style.width = "100%"; + proxyElem.style.height = "100%"; + proxyElem.style.zIndex = 10000; + proxyElem.style.display = "none"; + document.body.appendChild(proxyElem); + + // This is to make sure callers don't get confused by having + // our blocking element as the target + proxyElem.addEventListener('contextmenu', _captureProxy); + + proxyElem.addEventListener('mousemove', _captureProxy); + proxyElem.addEventListener('mouseup', _captureProxy); + } + + document.captureElement = target; + + // Track cursor and get initial cursor + _captureObserver.observe(target, {attributes: true}); + _capturedElemChanged(); + + proxyElem.style.display = ""; + + // We listen to events on window in order to keep tracking if it + // happens to leave the viewport + window.addEventListener('mousemove', _captureProxy); + window.addEventListener('mouseup', _captureProxy); + } +} + +export function releaseCapture() { + if (document.releaseCapture) { + + document.releaseCapture(); + document.captureElement = null; + + } else { + if (!document.captureElement) { + return; + } + + // There might be events already queued. The event proxy needs + // access to the captured element for these queued events. + // E.g. contextmenu (right-click) in Microsoft Edge + // + // Before removing the capturedElem pointer we save it to a + // temporary variable that the unflushed events can use. + _elementForUnflushedEvents = document.captureElement; + document.captureElement = null; + + _captureObserver.disconnect(); + + const proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + proxyElem.style.display = "none"; + + window.removeEventListener('mousemove', _captureProxy); + window.removeEventListener('mouseup', _captureProxy); + } +} diff --git a/engine/static/vendor/novnc/core/util/eventtarget.js b/engine/static/vendor/novnc/core/util/eventtarget.js new file mode 100644 index 00000000..547bf5fa --- /dev/null +++ b/engine/static/vendor/novnc/core/util/eventtarget.js @@ -0,0 +1,35 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +export default class EventTargetMixin { + constructor() { + this._listeners = new Map(); + } + + addEventListener(type, callback) { + if (!this._listeners.has(type)) { + this._listeners.set(type, new Set()); + } + this._listeners.get(type).add(callback); + } + + removeEventListener(type, callback) { + if (this._listeners.has(type)) { + this._listeners.get(type).delete(callback); + } + } + + dispatchEvent(event) { + if (!this._listeners.has(event.type)) { + return true; + } + this._listeners.get(event.type) + .forEach(callback => callback.call(this, event)); + return !event.defaultPrevented; + } +} diff --git a/engine/static/vendor/novnc/core/util/int.js b/engine/static/vendor/novnc/core/util/int.js new file mode 100644 index 00000000..303ddc5f --- /dev/null +++ b/engine/static/vendor/novnc/core/util/int.js @@ -0,0 +1,15 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +export function toUnsigned32bit(toConvert) { + return toConvert >>> 0; +} + +export function toSigned32bit(toConvert) { + return toConvert | 0; +} diff --git a/engine/static/vendor/novnc/core/util/logging.js b/engine/static/vendor/novnc/core/util/logging.js new file mode 100644 index 00000000..0db08385 --- /dev/null +++ b/engine/static/vendor/novnc/core/util/logging.js @@ -0,0 +1,56 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * Logging/debug routines + */ + +let _logLevel = 'warn'; + +let Debug = () => {}; +let Info = () => {}; +let Warn = () => {}; +let Error = () => {}; + +export function initLogging(level) { + if (typeof level === 'undefined') { + level = _logLevel; + } else { + _logLevel = level; + } + + Debug = Info = Warn = Error = () => {}; + + if (typeof window.console !== "undefined") { + /* eslint-disable no-console, no-fallthrough */ + switch (level) { + case 'debug': + Debug = console.debug.bind(window.console); + case 'info': + Info = console.info.bind(window.console); + case 'warn': + Warn = console.warn.bind(window.console); + case 'error': + Error = console.error.bind(window.console); + case 'none': + break; + default: + throw new window.Error("invalid logging type '" + level + "'"); + } + /* eslint-enable no-console, no-fallthrough */ + } +} + +export function getLogging() { + return _logLevel; +} + +export { Debug, Info, Warn, Error }; + +// Initialize logging level +initLogging(); diff --git a/engine/static/vendor/novnc/core/util/strings.js b/engine/static/vendor/novnc/core/util/strings.js new file mode 100644 index 00000000..432b0a9d --- /dev/null +++ b/engine/static/vendor/novnc/core/util/strings.js @@ -0,0 +1,28 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +// Decode from UTF-8 +export function decodeUTF8(utf8string, allowLatin1=false) { + try { + return decodeURIComponent(escape(utf8string)); + } catch (e) { + if (e instanceof URIError) { + if (allowLatin1) { + // If we allow Latin1 we can ignore any decoding fails + // and in these cases return the original string + return utf8string; + } + } + throw e; + } +} + +// Encode to UTF-8 +export function encodeUTF8(DOMString) { + return unescape(encodeURIComponent(DOMString)); +} diff --git a/engine/static/vendor/novnc/core/websock.js b/engine/static/vendor/novnc/core/websock.js new file mode 100644 index 00000000..ee8a4bc4 --- /dev/null +++ b/engine/static/vendor/novnc/core/websock.js @@ -0,0 +1,369 @@ +/* + * Websock: high-performance buffering wrapper + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * Websock is similar to the standard WebSocket / RTCDataChannel object + * but with extra buffer handling. + * + * Websock has built-in receive queue buffering; the message event + * does not contain actual data but is simply a notification that + * there is new data available. Several rQ* methods are available to + * read binary data off of the receive queue. + */ + +import * as Log from './util/logging.js'; + +// this has performance issues in some versions Chromium, and +// doesn't gain a tremendous amount of performance increase in Firefox +// at the moment. It may be valuable to turn it on in the future. +const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB + +// Constants pulled from RTCDataChannelState enum +// https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/readyState#RTCDataChannelState_enum +const DataChannel = { + CONNECTING: "connecting", + OPEN: "open", + CLOSING: "closing", + CLOSED: "closed" +}; + +const ReadyStates = { + CONNECTING: [WebSocket.CONNECTING, DataChannel.CONNECTING], + OPEN: [WebSocket.OPEN, DataChannel.OPEN], + CLOSING: [WebSocket.CLOSING, DataChannel.CLOSING], + CLOSED: [WebSocket.CLOSED, DataChannel.CLOSED], +}; + +// Properties a raw channel must have, WebSocket and RTCDataChannel are two examples +const rawChannelProps = [ + "send", + "close", + "binaryType", + "onerror", + "onmessage", + "onopen", + "protocol", + "readyState", +]; + +export default class Websock { + constructor() { + this._websocket = null; // WebSocket or RTCDataChannel object + + this._rQi = 0; // Receive queue index + this._rQlen = 0; // Next write position in the receive queue + this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB) + // called in init: this._rQ = new Uint8Array(this._rQbufferSize); + this._rQ = null; // Receive queue + + this._sQbufferSize = 1024 * 10; // 10 KiB + // called in init: this._sQ = new Uint8Array(this._sQbufferSize); + this._sQlen = 0; + this._sQ = null; // Send queue + + this._eventHandlers = { + message: () => {}, + open: () => {}, + close: () => {}, + error: () => {} + }; + } + + // Getters and setters + + get readyState() { + let subState; + + if (this._websocket === null) { + return "unused"; + } + + subState = this._websocket.readyState; + + if (ReadyStates.CONNECTING.includes(subState)) { + return "connecting"; + } else if (ReadyStates.OPEN.includes(subState)) { + return "open"; + } else if (ReadyStates.CLOSING.includes(subState)) { + return "closing"; + } else if (ReadyStates.CLOSED.includes(subState)) { + return "closed"; + } + + return "unknown"; + } + + // Receive queue + rQpeek8() { + return this._rQ[this._rQi]; + } + + rQskipBytes(bytes) { + this._rQi += bytes; + } + + rQshift8() { + return this._rQshift(1); + } + + rQshift16() { + return this._rQshift(2); + } + + rQshift32() { + return this._rQshift(4); + } + + // TODO(directxman12): test performance with these vs a DataView + _rQshift(bytes) { + let res = 0; + for (let byte = bytes - 1; byte >= 0; byte--) { + res += this._rQ[this._rQi++] << (byte * 8); + } + return res >>> 0; + } + + rQlen() { + return this._rQlen - this._rQi; + } + + rQshiftStr(len) { + let str = ""; + // Handle large arrays in steps to avoid long strings on the stack + for (let i = 0; i < len; i += 4096) { + let part = this.rQshiftBytes(Math.min(4096, len - i), false); + str += String.fromCharCode.apply(null, part); + } + return str; + } + + rQshiftBytes(len, copy=true) { + this._rQi += len; + if (copy) { + return this._rQ.slice(this._rQi - len, this._rQi); + } else { + return this._rQ.subarray(this._rQi - len, this._rQi); + } + } + + rQshiftTo(target, len) { + // TODO: make this just use set with views when using a ArrayBuffer to store the rQ + target.set(new Uint8Array(this._rQ.buffer, this._rQi, len)); + this._rQi += len; + } + + rQpeekBytes(len, copy=true) { + if (copy) { + return this._rQ.slice(this._rQi, this._rQi + len); + } else { + return this._rQ.subarray(this._rQi, this._rQi + len); + } + } + + // Check to see if we must wait for 'num' bytes (default to FBU.bytes) + // to be available in the receive queue. Return true if we need to + // wait (and possibly print a debug message), otherwise false. + rQwait(msg, num, goback) { + if (this._rQlen - this._rQi < num) { + if (goback) { + if (this._rQi < goback) { + throw new Error("rQwait cannot backup " + goback + " bytes"); + } + this._rQi -= goback; + } + return true; // true means need more data + } + return false; + } + + // Send queue + + sQpush8(num) { + this._sQensureSpace(1); + this._sQ[this._sQlen++] = num; + } + + sQpush16(num) { + this._sQensureSpace(2); + this._sQ[this._sQlen++] = (num >> 8) & 0xff; + this._sQ[this._sQlen++] = (num >> 0) & 0xff; + } + + sQpush32(num) { + this._sQensureSpace(4); + this._sQ[this._sQlen++] = (num >> 24) & 0xff; + this._sQ[this._sQlen++] = (num >> 16) & 0xff; + this._sQ[this._sQlen++] = (num >> 8) & 0xff; + this._sQ[this._sQlen++] = (num >> 0) & 0xff; + } + + sQpushString(str) { + let bytes = str.split('').map(chr => chr.charCodeAt(0)); + this.sQpushBytes(new Uint8Array(bytes)); + } + + sQpushBytes(bytes) { + for (let offset = 0;offset < bytes.length;) { + this._sQensureSpace(1); + + let chunkSize = this._sQbufferSize - this._sQlen; + if (chunkSize > bytes.length - offset) { + chunkSize = bytes.length - offset; + } + + this._sQ.set(bytes.subarray(offset, offset + chunkSize), this._sQlen); + this._sQlen += chunkSize; + offset += chunkSize; + } + } + + flush() { + if (this._sQlen > 0 && this.readyState === 'open') { + this._websocket.send(new Uint8Array(this._sQ.buffer, 0, this._sQlen)); + this._sQlen = 0; + } + } + + _sQensureSpace(bytes) { + if (this._sQbufferSize - this._sQlen < bytes) { + this.flush(); + } + } + + // Event handlers + off(evt) { + this._eventHandlers[evt] = () => {}; + } + + on(evt, handler) { + this._eventHandlers[evt] = handler; + } + + _allocateBuffers() { + this._rQ = new Uint8Array(this._rQbufferSize); + this._sQ = new Uint8Array(this._sQbufferSize); + } + + init() { + this._allocateBuffers(); + this._rQi = 0; + this._websocket = null; + } + + open(uri, protocols) { + this.attach(new WebSocket(uri, protocols)); + } + + attach(rawChannel) { + this.init(); + + // Must get object and class methods to be compatible with the tests. + const channelProps = [...Object.keys(rawChannel), ...Object.getOwnPropertyNames(Object.getPrototypeOf(rawChannel))]; + for (let i = 0; i < rawChannelProps.length; i++) { + const prop = rawChannelProps[i]; + if (channelProps.indexOf(prop) < 0) { + throw new Error('Raw channel missing property: ' + prop); + } + } + + this._websocket = rawChannel; + this._websocket.binaryType = "arraybuffer"; + this._websocket.onmessage = this._recvMessage.bind(this); + + this._websocket.onopen = () => { + Log.Debug('>> WebSock.onopen'); + if (this._websocket.protocol) { + Log.Info("Server choose sub-protocol: " + this._websocket.protocol); + } + + this._eventHandlers.open(); + Log.Debug("<< WebSock.onopen"); + }; + + this._websocket.onclose = (e) => { + Log.Debug(">> WebSock.onclose"); + this._eventHandlers.close(e); + Log.Debug("<< WebSock.onclose"); + }; + + this._websocket.onerror = (e) => { + Log.Debug(">> WebSock.onerror: " + e); + this._eventHandlers.error(e); + Log.Debug("<< WebSock.onerror: " + e); + }; + } + + close() { + if (this._websocket) { + if (this.readyState === 'connecting' || + this.readyState === 'open') { + Log.Info("Closing WebSocket connection"); + this._websocket.close(); + } + + this._websocket.onmessage = () => {}; + } + } + + // private methods + + // We want to move all the unread data to the start of the queue, + // e.g. compacting. + // The function also expands the receive que if needed, and for + // performance reasons we combine these two actions to avoid + // unnecessary copying. + _expandCompactRQ(minFit) { + // if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place + // instead of resizing + const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8; + const resizeNeeded = this._rQbufferSize < requiredBufferSize; + + if (resizeNeeded) { + // Make sure we always *at least* double the buffer size, and have at least space for 8x + // the current amount of data + this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize); + } + + // we don't want to grow unboundedly + if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { + this._rQbufferSize = MAX_RQ_GROW_SIZE; + if (this._rQbufferSize - (this._rQlen - this._rQi) < minFit) { + throw new Error("Receive queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); + } + } + + if (resizeNeeded) { + const oldRQbuffer = this._rQ.buffer; + this._rQ = new Uint8Array(this._rQbufferSize); + this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi)); + } else { + this._rQ.copyWithin(0, this._rQi, this._rQlen); + } + + this._rQlen = this._rQlen - this._rQi; + this._rQi = 0; + } + + // push arraybuffer values onto the end of the receive que + _recvMessage(e) { + if (this._rQlen == this._rQi) { + // All data has now been processed, this means we + // can reset the receive queue. + this._rQlen = 0; + this._rQi = 0; + } + const u8 = new Uint8Array(e.data); + if (u8.length > this._rQbufferSize - this._rQlen) { + this._expandCompactRQ(u8.length); + } + this._rQ.set(u8, this._rQlen); + this._rQlen += u8.length; + + if (this._rQlen - this._rQi > 0) { + this._eventHandlers.message(); + } else { + Log.Debug("Ignoring empty message"); + } + } +} diff --git a/engine/static/vendor/novnc/vendor/pako/LICENSE b/engine/static/vendor/novnc/vendor/pako/LICENSE new file mode 100644 index 00000000..d082ae32 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2014-2016 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/engine/static/vendor/novnc/vendor/pako/README.md b/engine/static/vendor/novnc/vendor/pako/README.md new file mode 100644 index 00000000..755df643 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/README.md @@ -0,0 +1,6 @@ +This is an ES6-modules-compatible version of +https://github.com/nodeca/pako, based on pako version 1.0.3. + +It's more-or-less a direct translation of the original, with unused parts +removed, and the dynamic support for non-typed arrays removed (since ES6 +modules don't work well with dynamic exports). diff --git a/engine/static/vendor/novnc/vendor/pako/lib/utils/common.js b/engine/static/vendor/novnc/vendor/pako/lib/utils/common.js new file mode 100644 index 00000000..576fd59d --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/utils/common.js @@ -0,0 +1,45 @@ +// reduce buffer size, avoiding mem copy +export function shrinkBuf (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +export function arraySet (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } +} + +// Join array of chunks to single array. +export function flattenChunks (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; +} + +export var Buf8 = Uint8Array; +export var Buf16 = Uint16Array; +export var Buf32 = Int32Array; diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/adler32.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/adler32.js new file mode 100644 index 00000000..058a534a --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/adler32.js @@ -0,0 +1,27 @@ +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It doesn't worth to make additional optimizationa as in original. +// Small size is preferable. + +export default function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/constants.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/constants.js new file mode 100644 index 00000000..7d80502d --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/constants.js @@ -0,0 +1,47 @@ +export default { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/crc32.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/crc32.js new file mode 100644 index 00000000..611ffb29 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/crc32.js @@ -0,0 +1,36 @@ +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + + +// Use ordinary array, since untyped makes no boost here +export default function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/deflate.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/deflate.js new file mode 100644 index 00000000..c3a5ba49 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/deflate.js @@ -0,0 +1,1846 @@ +import * as utils from "../utils/common.js"; +import * as trees from "./trees.js"; +import adler32 from "./adler32.js"; +import crc32 from "./crc32.js"; +import msg from "./messages.js"; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +export const Z_NO_FLUSH = 0; +export const Z_PARTIAL_FLUSH = 1; +//export const Z_SYNC_FLUSH = 2; +export const Z_FULL_FLUSH = 3; +export const Z_FINISH = 4; +export const Z_BLOCK = 5; +//export const Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +export const Z_OK = 0; +export const Z_STREAM_END = 1; +//export const Z_NEED_DICT = 2; +//export const Z_ERRNO = -1; +export const Z_STREAM_ERROR = -2; +export const Z_DATA_ERROR = -3; +//export const Z_MEM_ERROR = -4; +export const Z_BUF_ERROR = -5; +//export const Z_VERSION_ERROR = -6; + + +/* compression levels */ +//export const Z_NO_COMPRESSION = 0; +//export const Z_BEST_SPEED = 1; +//export const Z_BEST_COMPRESSION = 9; +export const Z_DEFAULT_COMPRESSION = -1; + + +export const Z_FILTERED = 1; +export const Z_HUFFMAN_ONLY = 2; +export const Z_RLE = 3; +export const Z_FIXED = 4; +export const Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//export const Z_BINARY = 0; +//export const Z_TEXT = 1; +//export const Z_ASCII = 1; // = Z_TEXT +export const Z_UNKNOWN = 2; + + +/* The deflate compression method */ +export const Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + // Do nothing + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + // Do nothing + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +export { deflateInit, deflateInit2, deflateReset, deflateResetKeep, deflateSetHeader, deflate, deflateEnd, deflateSetDictionary }; +export var deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/gzheader.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/gzheader.js new file mode 100644 index 00000000..2ec586d3 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/gzheader.js @@ -0,0 +1,35 @@ +export default function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/inffast.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/inffast.js new file mode 100644 index 00000000..889dcc7a --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/inffast.js @@ -0,0 +1,324 @@ +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +export default function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/inflate.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/inflate.js new file mode 100644 index 00000000..1d2063bc --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/inflate.js @@ -0,0 +1,1527 @@ +import * as utils from "../utils/common.js"; +import adler32 from "./adler32.js"; +import crc32 from "./crc32.js"; +import inflate_fast from "./inffast.js"; +import inflate_table from "./inftrees.js"; + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//export const Z_NO_FLUSH = 0; +//export const Z_PARTIAL_FLUSH = 1; +//export const Z_SYNC_FLUSH = 2; +//export const Z_FULL_FLUSH = 3; +export const Z_FINISH = 4; +export const Z_BLOCK = 5; +export const Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +export const Z_OK = 0; +export const Z_STREAM_END = 1; +export const Z_NEED_DICT = 2; +//export const Z_ERRNO = -1; +export const Z_STREAM_ERROR = -2; +export const Z_DATA_ERROR = -3; +export const Z_MEM_ERROR = -4; +export const Z_BUF_ERROR = -5; +//export const Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +export const Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more conveniend processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' insdead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +export { inflateReset, inflateReset2, inflateResetKeep, inflateInit, inflateInit2, inflate, inflateEnd, inflateGetHeader, inflateSetDictionary }; +export var inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/inftrees.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/inftrees.js new file mode 100644 index 00000000..78b7c9eb --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/inftrees.js @@ -0,0 +1,322 @@ +import * as utils from "../utils/common.js"; + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +export default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/messages.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/messages.js new file mode 100644 index 00000000..f95cb704 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/messages.js @@ -0,0 +1,11 @@ +export default { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/trees.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/trees.js new file mode 100644 index 00000000..a69b8a59 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/trees.js @@ -0,0 +1,1195 @@ +import * as utils from "../utils/common.js"; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +export { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align }; diff --git a/engine/static/vendor/novnc/vendor/pako/lib/zlib/zstream.js b/engine/static/vendor/novnc/vendor/pako/lib/zlib/zstream.js new file mode 100644 index 00000000..e7e674e7 --- /dev/null +++ b/engine/static/vendor/novnc/vendor/pako/lib/zlib/zstream.js @@ -0,0 +1,24 @@ +export default function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} diff --git a/engine/tests/test_app.py b/engine/tests/test_app.py new file mode 100644 index 00000000..81de22fa --- /dev/null +++ b/engine/tests/test_app.py @@ -0,0 +1,1649 @@ +"""HTTP and WebSocket boundary tests without a real remote libvirt host.""" + +from __future__ import annotations + +import re +import stat +import sys +import threading +import time +import types +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi.testclient import TestClient +from starlette.websockets import WebSocketDisconnect +from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware + + +# The API is injected with FakeVMService. Test machines need no native libvirt. +try: + import libvirt # noqa: F401 +except ModuleNotFoundError: + stub = types.ModuleType("libvirt") + stub.libvirtError = type("libvirtError", (Exception,), {}) + sys.modules["libvirt"] = stub + +from virsh_panel.app import create_app # noqa: E402 +from virsh_panel.cloud_templates import ( # noqa: E402 + TemplateError, TemplateStore, template_id_for, template_scope, + template_volume_name, +) +from virsh_panel.config import Settings # noqa: E402 +from virsh_panel.libvirt_service import VMError # noqa: E402 +from virsh_panel.metrics import host_scope, query_interval_seconds # noqa: E402 +from virsh_panel.panel_state import PanelState # noqa: E402 +from virsh_panel.remote_host import RemoteHostError, validate_public_pool # noqa: E402 + + +PASSWORD = "correct-horse-battery-staple" +GUEST_PASSWORD = "A-strong-guest-password-2026" +VM_ID = "00000000-0000-4000-8000-000000000001" +ORIGIN = "https://panel.example.test" +STATIC_DIR = Path(__file__).resolve().parents[1] / "static" +CREATE_BODY = { + "name": "alma-test", "vcpu": 2, "memory_mib": 2048, "disk_gib": 20, + "network": "default", "iso": "AlmaLinux-10.iso", +} +CLOUD_CREATE_BODY = { + "source": "cloud", "template_id": "alma10-template", + "name": "cloud-vm", "vcpu": 2, "memory_mib": 2048, "disk_gib": 20, + "network": "bridge:br0", "public_ip_cidr": "8.8.8.18/24", + "gateway": "8.8.8.1", "dns_servers": ["1.1.1.1"], + "guest_ssh_public_key": ( + "ssh-ed25519 " + "AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 " + "panel-test" + ), +} +OFFICIAL_CLOUD_URL = ( + "https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/" + "AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2" +) +OFFICIAL_ALMA9_URL = ( + "https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/" + "AlmaLinux-9-GenericCloud-latest.x86_64.qcow2" +) +HOST_BODY = { + "host": "vmhost.example.test", "port": 2222, + "private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----", + "host_key": "vp-managed ssh-ed25519 AAAATEST", + "confirmed_fingerprint": "SHA256:example", + "storage_pool": "images", "iso_pool": "iso", + "rescue_iso_pool": "rescue", "default_network": "default", +} + + +class FakeVMService: + def __init__(self) -> None: + self.calls: list[tuple] = [] + self.resource_error = False + self.list_error = False + self.reinstall_gate: threading.Event | None = None + self.reinstall_started = threading.Event() + self.rescue_enter_error: VMError | None = None + self.rescue_pending_manual_restart = False + self.vm = { + "uuid": VM_ID, "name": "alma-test", "state": "running", "vcpu": 2, + "memory_mib": 2048, "disks": [], "autostart": False, + } + self.other_vms: list[dict] = [] + + def resources(self): + self.calls.append(("resources",)) + if self.resource_error: + raise VMError("ISO 池尚未就绪", 409) + return {"networks": ["default"], "isos": ["AlmaLinux-10.iso"], + "storage_pool": "images"} + + def ensure_storage_pools(self): + self.calls.append(("ensure_storage_pools",)) + return {"storage_pool": "panel-dir-kvm", "iso_pool": "panel-dir-iso"} + + def list_vms(self): + self.calls.append(("list_vms",)) + if self.list_error: + raise VMError("libvirt API 不可用", 502) + return [self.vm, *self.other_vms] + + def get_vm(self, vm_id): + self.calls.append(("get_vm", vm_id)) + if vm_id != self.vm["uuid"]: + raise VMError("虚拟机不存在", 404) + return self.vm + + def create_vm(self, spec): + self.calls.append(("create_vm", spec)) + return self.vm + + def create_cloud_vm(self, spec, template_volume_name): + self.calls.append(("create_cloud_vm", spec, template_volume_name)) + if self.vm.get("os_source") == "cloud_template": + self.other_vms.append(self.vm.copy()) + self.vm = { + **self.vm, "uuid": spec["vm_uuid"], "name": spec["name"], + "managed": True, "os_source": "cloud_template", + "public_ip_cidr": spec["public_ip_cidr"], "os_name": spec["os_name"], + "credential_generation": f"panel-seed-{spec['vm_uuid']}.iso", + } + return self.vm + + def reinstall_cloud_vm(self, vm_id, template_volume_name, *, + os_name=None, ssh_public_key="", root_password_hash=None, + progress=None): + self.calls.append(("reinstall_cloud_vm", vm_id, template_volume_name, + ssh_public_key, root_password_hash, os_name)) + self.reinstall_started.set() + if self.reinstall_gate is not None: + assert self.reinstall_gate.wait(timeout=5), "test did not release reinstall job" + if progress is not None: + progress("completed") + generation = f"panel-seed-reinstall-{len(self.calls)}.iso" + self.vm["credential_generation"] = generation + return {"vm": self.vm, "credential_generation": generation} + + def import_template(self, image_path, volume_name, virtual_size): + self.calls.append(("import_template", volume_name, virtual_size)) + return {"volume_name": volume_name, "virtual_size": virtual_size, + "image_bytes": image_path.stat().st_size} + + def import_rescue_iso(self, image_path, volume_name): + self.calls.append(("import_rescue_iso", volume_name, image_path.stat().st_size)) + return {"volume_name": volume_name, "image_bytes": image_path.stat().st_size} + + def delete_rescue_iso(self, volume_name): + self.calls.append(("delete_rescue_iso", volume_name)) + return {"volume_name": volume_name, "deleted": True} + + def prepare_rescue_vm(self, vm_id, volume_name): + self.calls.append(("prepare_rescue_vm", vm_id, volume_name)) + if self.vm.get("rescue_mode") or self.vm.get("rescue_staged"): + raise VMError("已经处于救援模式", 409) + return f'{self.vm["name"]}' + + def enter_rescue_vm(self, vm_id, volume_name, original_xml): + self.calls.append(("enter_rescue_vm", vm_id, volume_name, original_xml)) + if self.rescue_enter_error is not None: + raise self.rescue_enter_error + if self.rescue_pending_manual_restart: + self.vm["rescue_staged"] = True + self.vm["rescue_mode"] = False + return {"vm": self.vm, "pending_manual_restart": True, + "warning": "救援 ISO 已配置为下次冷启动;请手动强制断电后开机"} + self.vm["rescue_mode"] = True + self.vm["rescue_staged"] = False + self.vm["rescue_volume_name"] = volume_name + return {"vm": self.vm} + + def exit_rescue_vm(self, vm_id, original_xml): + self.calls.append(("exit_rescue_vm", vm_id, original_xml)) + self.vm["rescue_mode"] = False + self.vm["rescue_staged"] = False + self.vm["rescue_volume_name"] = None + self.vm["state"] = "running" + return {"vm": self.vm} + + def force_start_staged_rescue_vm(self, vm_id, original_xml): + self.calls.append(("force_start_staged_rescue_vm", vm_id, original_xml)) + if not self.vm.get("rescue_staged"): + raise VMError("救援 ISO 尚未预挂载", 409) + self.vm["state"] = "running" + self.vm["rescue_staged"] = False + self.vm["rescue_mode"] = True + return {"vm": self.vm} + + def action(self, vm_id, action): + self.calls.append(("action", vm_id, action)) + if self.vm.get("rescue_staged") and action == "poweroff": + self.vm["state"] = "shutoff" + self.vm["rescue_mode"] = True + elif self.vm.get("rescue_staged") and action == "start": + self.vm["state"] = "running" + self.vm["rescue_mode"] = True + self.vm["rescue_staged"] = False + return self.vm + + def delete_vm(self, vm_id, delete_disks): + self.calls.append(("delete_vm", vm_id, delete_disks)) + return {"uuid": vm_id, "deleted": True, "deleted_disks": []} + + def console_port(self, vm_id): + self.calls.append(("console_port", vm_id)) + return 5907 + + +class FakeRemoteManager: + def __init__(self) -> None: + self.calls: list[tuple] = [] + self.profile: dict | None = None + self.staged_profiles: list = [] + self.unlock_passphrase: str | None = None + + def current(self): + return self.profile + + def scan(self, host, port): + self.calls.append(("scan", host, port)) + return {"host": host, "port": port, "key_type": "ssh-ed25519", + "fingerprint": "SHA256:example", "known_hosts_line": HOST_BODY["host_key"]} + + def stage(self, profile, confirmed_fingerprint): + validate_public_pool( + profile.public_pool_cidr, profile.public_gateway, + profile.public_dns_servers, profile.public_reserved_ips, profile.host, + profile.public_vm_prefix, + ) + self.calls.append(("stage", profile.host, profile.port, confirmed_fingerprint)) + self.staged_profiles.append(profile) + return SimpleNamespace( + libvirt_uri="qemu+ssh://root@vp-managed/system?command=staged", + profile=profile, + ) + + def test(self, staged): + self.calls.append(("test", staged.libvirt_uri)) + return {"ok": True, "ssh": "connected", "libvirt": "available"} + + def abort(self, staged): + self.calls.append(("abort", staged.libvirt_uri)) + + def commit(self, staged): + self.calls.append(("commit", staged.libvirt_uri)) + self.unlock_passphrase = staged.profile.private_key_passphrase or None + self.profile = { + "host": staged.profile.host, "port": staged.profile.port, + "key_type": "ssh-ed25519", "fingerprint": "SHA256:example", + "private_key_configured": True, + "private_key_encrypted": bool(self.unlock_passphrase), "key_locked": False, + "private_key_passphrase_saved": bool(self.unlock_passphrase), + "storage_pool": staged.profile.storage_pool, + "iso_pool": staged.profile.iso_pool, + "rescue_iso_pool": staged.profile.rescue_iso_pool, + "default_network": staged.profile.default_network, + "region": staged.profile.region, + "public_pool_cidr": getattr(staged.profile, "public_pool_cidr", ""), + "public_gateway": getattr(staged.profile, "public_gateway", ""), + "public_dns_servers": list(getattr(staged.profile, "public_dns_servers", [])), + "public_reserved_ips": list(getattr(staged.profile, "public_reserved_ips", [])), + "public_vm_prefix": getattr(staged.profile, "public_vm_prefix", None), + "libvirt_uri": "qemu+ssh://root@vp-managed/system?no_tty=1&command=/fake/ssh-wrapper", + "ssh_target": "vp-managed", "ssh_config_file": "/fake/config", + "ssh_known_hosts_file": "/fake/known_hosts", + } + return self.profile + + def unlock_current(self, passphrase): + self.calls.append(("unlock_current", passphrase)) + if passphrase != self.unlock_passphrase or self.profile is None: + raise RemoteHostError("私钥口令错误", 400) + self.profile["key_locked"] = False + return self.profile + + +@pytest.fixture +def web(tmp_path): + state = PanelState(tmp_path / "panel-data") + service = FakeVMService() + manager = FakeRemoteManager() + seen_profiles: list[dict] = [] + + def service_factory(profile): + seen_profiles.append(profile) + return service + + settings = Settings(data_dir=state.data_dir, static_dir=STATIC_DIR) + app = create_app(settings, panel_state=state, remote_manager=manager, + service_factory=service_factory) + token = state.token_file.read_text(encoding="ascii").strip() + with TestClient( + app, + base_url=ORIGIN, + ) as client: + yield client, state, token, service, manager, seen_profiles + + +def test_first_start_creates_token_and_restarts_reuse_it(tmp_path): + state = PanelState(tmp_path / "panel-data") + settings = Settings(data_dir=state.data_dir, static_dir=STATIC_DIR) + manager = FakeRemoteManager() + with patch("virsh_panel.app.STARTUP_LOG.warning") as warning: + create_app(settings, panel_state=state, remote_manager=manager) + token = state.token_file.read_text(encoding="ascii").strip() + assert warning.call_args.args == ("VIRSH_PANEL_SETUP_TOKEN=%s", token) + assert len(token) >= 32 + + create_app(settings, panel_state=PanelState(state.data_dir), remote_manager=manager) + assert state.token_file.read_text(encoding="ascii").strip() == token + assert warning.call_count == 2 + + state.create_admin(token, "admin", PASSWORD) + create_app(settings, panel_state=PanelState(state.data_dir), remote_manager=manager) + assert warning.call_count == 2 + assert not state.token_file.exists() + + +def test_lifespan_closes_real_manager_interface(tmp_path): + state = PanelState(tmp_path / "panel-data") + settings = Settings(data_dir=state.data_dir, static_dir=STATIC_DIR) + manager = FakeRemoteManager() + closed: list[bool] = [] + manager.close = lambda: closed.append(True) + app = create_app(settings, panel_state=state, remote_manager=manager) + + with TestClient(app, base_url=ORIGIN) as client: + assert client.get("/api/v1/health").status_code == 200 + assert closed == [] + assert closed == [True] + + +def setup_admin(client: TestClient, token: str) -> str: + response = client.post("/api/v1/setup/admin", json={ + "token": token, "username": "admin", "password": PASSWORD, + }) + assert response.status_code == 200 + return response.json()["csrf_token"] + + +def login(client: TestClient) -> str: + response = client.post("/api/v1/login", json={"username": "admin", "password": PASSWORD}) + assert response.status_code == 200 + return response.json()["csrf_token"] + + +def configure_host(client: TestClient, csrf: str) -> dict: + response = client.put("/api/v1/host", json=HOST_BODY, headers={"X-CSRF-Token": csrf}) + assert response.status_code == 200 + return response.json() + + +def wait_for_import_job(client: TestClient, job_id: str) -> dict: + for _ in range(100): + response = client.get(f"/api/v1/vm-templates/import-jobs/{job_id}") + assert response.status_code == 200 + result = response.json() + if result["status"] != "running": + return result + time.sleep(0.01) + pytest.fail("云镜像导入任务未在测试等待时间内结束") + + +def wait_for_reinstall_job(client: TestClient, job_id: str, csrf: str) -> dict: + for _ in range(100): + response = client.get( + f"/api/v1/reinstall-jobs/{job_id}", + headers={"X-CSRF-Token": csrf}, + ) + assert response.status_code == 200 + result = response.json() + if result["status"] not in ("queued", "running"): + return result + time.sleep(0.01) + pytest.fail("重装任务未在测试等待时间内结束") + + +def configure_reinstall_case(web): + client, state, token, service, manager, _ = web + csrf = setup_admin(client, token) + assert client.put( + "/api/v1/host", json={**HOST_BODY, "default_network": "bridge:br0"}, + headers={"X-CSRF-Token": csrf}, + ).status_code == 200 + scope = template_scope(manager.current()) + template_id = template_id_for(scope, "d" * 64) + volume_name = template_volume_name(template_id) + TemplateStore(state.data_dir).add( + scope, {"id": template_id, "volume_name": volume_name, "name": "AlmaLinux 10"}, + ) + service.vm.update({ + "name": "cloud-vm", "managed": True, "os_source": "cloud_template", + "public_ip_cidr": "8.8.8.18/24", "credential_generation": "legacy-seed.iso", + }) + return csrf, template_id, volume_name + + +def test_setup_token_is_single_use_and_admin_survives_restart(web): + client, state, token, service, manager, _ = web + assert client.get("/api/v1/setup/status").json() == {"setup_required": True} + assert client.get("/api/v1/vms").status_code == 401 + assert client.post("/api/v1/login", json={"username": "admin", "password": PASSWORD}).status_code == 409 + wrong = client.post("/api/v1/setup/admin", json={ + "token": "wrong", "username": "admin", "password": PASSWORD, + }) + assert wrong.status_code == 403 + csrf = setup_admin(client, token) + assert csrf + cookie = client.cookies.get("virsh_panel_session") + assert cookie + header = client.post("/api/v1/logout", headers={"X-CSRF-Token": csrf}).headers["set-cookie"] + assert "virsh_panel_session=" in header + assert client.get("/api/v1/setup/status").json() == {"setup_required": False} + assert not state.token_file.exists() + assert stat.S_IMODE(state.state_file.stat().st_mode) == 0o600 + assert state.initialize_setup_token() is None + assert PanelState(state.data_dir).admin()[0] == "admin" + assert client.post("/api/v1/setup/admin", json={ + "token": token, "username": "other", "password": PASSWORD, + }).status_code == 409 + assert login(client) + assert service.calls == [] and manager.calls == [] + + +def test_login_cookie_csrf_and_logout(web): + client, _, token, service, manager, _ = web + setup_admin(client, token) + assert client.post("/api/v1/login", json={"username": "admin", "password": "bad"}).status_code == 401 + response = client.post("/api/v1/login", json={"username": "admin", "password": PASSWORD}) + csrf = response.json()["csrf_token"] + cookie = response.headers["set-cookie"].lower() + assert "httponly" in cookie and "secure" in cookie and "samesite=strict" in cookie + assert client.get("/api/v1/session").json()["authenticated"] is True + assert client.post("/api/v1/logout").status_code == 403 + assert client.post("/api/v1/logout", headers={"X-CSRF-Token": csrf}).status_code == 200 + assert client.get("/api/v1/session").json()["authenticated"] is False + assert service.calls == [] and manager.calls == [] + + +def test_raw_x_real_ip_cannot_reset_login_limit(web): + client, _, token, *_ = web + setup_admin(client, token) + for index in range(5): + response = client.post( + "/api/v1/login", + json={"username": "admin", "password": "wrong"}, + headers={"X-Real-IP": f"198.51.100.{index + 1}"}, + ) + assert response.status_code == 401 + blocked = client.post( + "/api/v1/login", + json={"username": "admin", "password": PASSWORD}, + headers={"X-Real-IP": "203.0.113.99"}, + ) + assert blocked.status_code == 429 + + +def test_host_scan_test_save_and_secret_is_never_returned(web): + client, _, token, service, manager, seen = web + csrf = setup_admin(client, token) + assert client.get("/api/v1/host").json() == {"configured": False} + assert client.get("/api/v1/vms").status_code == 409 + assert client.post("/api/v1/host/scan", json={"host": HOST_BODY["host"], "port": 2222}).status_code == 403 + headers = {"X-CSRF-Token": csrf} + scan = client.post("/api/v1/host/scan", json={"host": HOST_BODY["host"], "port": 2222}, headers=headers) + assert scan.json()["fingerprint"] == "SHA256:example" + tested = client.post("/api/v1/host/test", json=HOST_BODY, headers=headers) + assert tested.status_code == 200 + assert tested.json()["resources"]["storage_pool"] == "images" + assert manager.current() is None + saved = configure_host(client, csrf) + assert saved["configured"] is True + assert saved["private_key_configured"] is True + assert "private_key" not in saved and "host_key" not in saved + assert "ssh_config_file" not in saved and "libvirt_uri" not in saved + assert saved["warnings"] == [] + assert client.get("/api/v1/host").json() == {k: v for k, v in saved.items() if k != "warnings"} + assert seen[0]["libvirt_uri"].endswith("command=staged") + assert seen[-1]["libvirt_uri"].endswith("command=staged") + assert manager.calls.count(("commit", manager.calls[-1][1])) == 1 + assert service.calls == [("list_vms",), ("resources",), + ("list_vms",), ("ensure_storage_pools",), + ("resources",)] + + +def test_host_region_is_returned_with_host_and_vms(web): + client, _, token, _service, _manager, _ = web + csrf = setup_admin(client, token) + body = {**HOST_BODY, "region": "中国香港"} + headers = {"X-CSRF-Token": csrf} + assert client.put("/api/v1/host", json=body, headers=headers).json()["region"] == "中国香港" + assert client.get("/api/v1/host").json()["region"] == "中国香港" + assert client.get("/api/v1/vms").json()["items"][0]["region"] == "中国香港" + assert client.get(f"/api/v1/vms/{VM_ID}").json()["region"] == "中国香港" + assert client.post("/api/v1/vms", json=CREATE_BODY, + headers=headers).json()["region"] == "中国香港" + assert client.put("/api/v1/host", json={**body, "region": "a\nline"}, + headers=headers).status_code == 422 + + +def test_host_public_pool_round_trips_and_rejects_invalid_networks(web): + client, _, token, _service, manager, _ = web + csrf = setup_admin(client, token) + headers = {"X-CSRF-Token": csrf} + body = { + **HOST_BODY, + "host": "8.8.8.3", + "default_network": "bridge:br0", + "public_pool_cidr": "8.8.8.0/24", + "public_gateway": "8.8.8.1", + "public_dns_servers": ["1.1.1.1", "8.8.4.4"], + "public_reserved_ips": ["8.8.8.2", "8.8.8.5"], + } + tested = client.post("/api/v1/host/test", json=body, headers=headers) + assert tested.status_code == 200 + saved = client.put("/api/v1/host", json=body, headers=headers) + assert saved.status_code == 200 + current = client.get("/api/v1/host") + assert current.status_code == 200 + for key in ("public_pool_cidr", "public_gateway", "public_dns_servers", + "public_reserved_ips"): + assert getattr(manager.staged_profiles[0], key) == body[key] + assert saved.json()[key] == current.json()[key] == body[key] + assert manager.current()[key] == body[key] + + for changes in ( + {"public_pool_cidr": "8.8.8.18/24"}, + {"public_pool_cidr": "8.8.8.0/23"}, + {"public_vm_prefix": 25}, + {"public_vm_prefix": 23}, + {"public_pool_cidr": "10.0.0.0/24", "public_gateway": "10.0.0.1"}, + {"public_gateway": "9.9.9.1"}, + {"public_dns_servers": ["invalid-dns"]}, + {"public_reserved_ips": ["9.9.9.2"]}, + ): + rejected = client.put("/api/v1/host", json={**body, **changes}, headers=headers) + assert rejected.status_code in (400, 422) + assert manager.current()["public_pool_cidr"] == body["public_pool_cidr"] + + +def test_host_accepts_provider_28_and_gateway_address_form(web): + client, _, token, _service, manager, _ = web + csrf = setup_admin(client, token) + body = { + **HOST_BODY, + "host": "123.123.123.113", + "default_network": "bridge:br0", + "public_pool_cidr": "123.123.123.113/28", + "public_gateway": "123.123.123.113", + "public_dns_servers": ["1.1.1.1"], + "public_reserved_ips": ["123.123.123.114"], + "public_vm_prefix": 24, + } + headers = {"X-CSRF-Token": csrf} + assert client.post("/api/v1/host/test", json=body, headers=headers).status_code == 200 + assert client.put("/api/v1/host", json=body, headers=headers).status_code == 200 + assert manager.current()["public_pool_cidr"] == body["public_pool_cidr"] + assert manager.current()["public_vm_prefix"] == 24 + + +def test_private_key_passphrase_reaches_host_profile_but_is_never_echoed(web): + client, _, token, _, manager, _ = web + csrf = setup_admin(client, token) + secret = "a strong SSH key passphrase" + body = {**HOST_BODY, "private_key_passphrase": secret} + headers = {"X-CSRF-Token": csrf} + + tested = client.post("/api/v1/host/test", json=body, headers=headers) + saved = client.put("/api/v1/host", json=body, headers=headers) + current = client.get("/api/v1/host") + assert tested.status_code == saved.status_code == current.status_code == 200 + assert len(manager.staged_profiles) == 2 + assert all(profile.private_key_passphrase == secret + for profile in manager.staged_profiles) + assert all(secret not in response.text for response in (tested, saved, current)) + assert saved.json()["private_key_encrypted"] is True + assert saved.json()["private_key_passphrase_saved"] is True + assert current.json()["private_key_passphrase_saved"] is True + assert "private_key_passphrase" not in manager.current() + + +def test_locked_host_returns_423_and_unlock_requires_csrf(web): + client, _, token, service, manager, _ = web + csrf = setup_admin(client, token) + secret = "only held in memory" + body = {**HOST_BODY, "private_key_passphrase": secret} + saved = client.put("/api/v1/host", json=body, headers={"X-CSRF-Token": csrf}) + assert saved.status_code == 200 + manager.profile["key_locked"] = True + service.calls.clear() + + current = client.get("/api/v1/host") + locked_vms = client.get("/api/v1/vms") + assert current.status_code == 200 + assert current.json()["key_locked"] is True + assert locked_vms.status_code == 423 + assert locked_vms.json()["error_code"] == "key_locked" + assert service.calls == [] + + no_csrf = client.post("/api/v1/host/unlock", json={"passphrase": secret}) + wrong = client.post("/api/v1/host/unlock", json={"passphrase": "wrong"}, + headers={"X-CSRF-Token": csrf}) + unlocked = client.post("/api/v1/host/unlock", json={"passphrase": secret}, + headers={"X-CSRF-Token": csrf}) + assert no_csrf.status_code == 403 + assert wrong.status_code == 400 + assert unlocked.status_code == 200 + assert unlocked.json()["key_locked"] is False + assert secret not in unlocked.text + assert client.get("/api/v1/vms").status_code == 200 + assert manager.calls[-1] == ("unlock_current", secret) + + +def test_unlock_limits_wrong_passphrase_attempts(web): + client, _, token, _, manager, _ = web + csrf = setup_admin(client, token) + secret = "only held in memory" + body = {**HOST_BODY, "private_key_passphrase": secret} + assert client.put("/api/v1/host", json=body, headers={"X-CSRF-Token": csrf}).status_code == 200 + manager.profile["key_locked"] = True + headers = {"X-CSRF-Token": csrf} + + for _ in range(5): + assert client.post("/api/v1/host/unlock", json={"passphrase": "wrong"}, + headers=headers).status_code == 400 + blocked = client.post("/api/v1/host/unlock", json={"passphrase": secret}, + headers=headers) + assert blocked.status_code == 429 + assert manager.profile["key_locked"] is True + + +def test_directory_pool_selectors_are_ensured_only_on_save(web): + client, _, token, service, manager, _ = web + csrf = setup_admin(client, token) + body = {**HOST_BODY, "storage_pool": "/home/kvm", "iso_pool": "/home/iso", + "rescue_iso_pool": "/home/rescue-iso"} + headers = {"X-CSRF-Token": csrf} + + tested = client.post("/api/v1/host/test", json=body, headers=headers) + assert tested.status_code == 200 + assert service.calls == [("list_vms",), ("resources",)] + assert manager.current() is None + + saved = client.put("/api/v1/host", json=body, headers=headers) + assert saved.status_code == 200 + assert saved.json()["storage_pool"] == "/home/kvm" + assert saved.json()["iso_pool"] == "/home/iso" + assert saved.json()["rescue_iso_pool"] == "/home/rescue-iso" + assert service.calls == [ + ("list_vms",), ("resources",), + ("list_vms",), ("ensure_storage_pools",), ("resources",), + ] + + +def test_rescue_template_upload_requires_separate_host_pool(web): + client, _, token, _, _, _ = web + csrf = setup_admin(client, token) + headers = {"X-CSRF-Token": csrf} + saved = client.put("/api/v1/host", json={**HOST_BODY, "rescue_iso_pool": ""}, + headers=headers) + assert saved.status_code == 200, saved.text + assert saved.json()["rescue_iso_pool"] == "" + assert client.get("/api/v1/resources").status_code == 200 + assert client.post("/api/v1/vms", json=CREATE_BODY, headers=headers).status_code == 201 + response = client.get("/api/v1/rescue-templates") + assert response.status_code == 409 + assert "救援 ISO 目录" in response.json()["error"] + response = client.post("/api/v1/rescue-templates?name=Rescue", + content=b"not an iso", headers=headers) + assert response.status_code == 409 + + +def test_explicit_bridge_selector_round_trips_through_host_api(web): + client, _, token, _, manager, seen = web + csrf = setup_admin(client, token) + body = {**HOST_BODY, "default_network": "bridge:br0"} + headers = {"X-CSRF-Token": csrf} + + tested = client.post("/api/v1/host/test", json=body, headers=headers) + saved = client.put("/api/v1/host", json=body, headers=headers) + assert tested.status_code == saved.status_code == 200 + assert all(profile.default_network == "bridge:br0" + for profile in manager.staged_profiles) + assert seen[-1]["default_network"] == "bridge:br0" + assert saved.json()["default_network"] == "bridge:br0" + assert client.get("/api/v1/host").json()["default_network"] == "bridge:br0" + + +def test_missing_resource_pool_warns_but_allows_host_connection(web): + client, _, token, service, manager, _ = web + csrf = setup_admin(client, token) + service.resource_error = True + headers = {"X-CSRF-Token": csrf} + tested = client.post("/api/v1/host/test", json=HOST_BODY, headers=headers) + assert tested.status_code == 200 + assert tested.json()["resources"] is None + assert tested.json()["warnings"] == ["ISO 池尚未就绪"] + assert manager.current() is None + saved = client.put("/api/v1/host", json=HOST_BODY, headers=headers) + assert saved.status_code == 200 + assert saved.json()["configured"] is True + assert saved.json()["warnings"] == ["ISO 池尚未就绪"] + + +def test_failed_libvirt_api_check_preserves_existing_host(web): + client, _, token, service, manager, _ = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + previous = manager.current() + commits = manager.calls.count(("commit", "qemu+ssh://root@vp-managed/system?command=staged")) + service.list_error = True + response = client.put("/api/v1/host", json=HOST_BODY, headers={"X-CSRF-Token": csrf}) + assert response.status_code == 502 + assert manager.current() is previous + assert manager.calls.count(("commit", "qemu+ssh://root@vp-managed/system?command=staged")) == commits + assert manager.calls[-1][0] == "abort" + + +def test_vm_crud_actions_and_error_mapping(web): + client, _, token, service, _, seen = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + service.calls.clear() + seen.clear() + headers = {"X-CSRF-Token": csrf} + assert client.get("/api/v1/resources").json()["isos"] == ["AlmaLinux-10.iso"] + assert client.get("/api/v1/vms").json()["items"][0]["uuid"] == VM_ID + assert client.get(f"/api/v1/vms/{VM_ID}").json()["name"] == "alma-test" + missing = client.get("/api/v1/vms/missing") + assert missing.status_code == 404 and missing.json() == {"error": "虚拟机不存在"} + assert client.post("/api/v1/vms", json=CREATE_BODY).status_code == 403 + assert client.post("/api/v1/vms", json={**CREATE_BODY, "vcpu": 0}, headers=headers).status_code == 422 + created = client.post("/api/v1/vms", json=CREATE_BODY, headers=headers) + assert created.status_code == 201 and created.json()["uuid"] == VM_ID + action = client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"}, headers=headers) + assert action.status_code == 200 + deleted = client.delete(f"/api/v1/vms/{VM_ID}?delete_disks=true", headers=headers) + assert deleted.status_code == 200 and deleted.json()["deleted"] is True + assert service.calls == [ + ("resources",), ("list_vms",), ("get_vm", VM_ID), ("get_vm", "missing"), + ("create_vm", CREATE_BODY), ("get_vm", VM_ID), + ("action", VM_ID, "reboot"), ("get_vm", VM_ID), + ("delete_vm", VM_ID, True), + ] + assert all("command=/fake/ssh-wrapper" in p["libvirt_uri"] for p in seen) + + +def test_vm_create_uses_vcpu_without_a_separate_nic_queue_field(web): + client, _, token, service, _, _ = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + headers = {"X-CSRF-Token": csrf} + body = {**CREATE_BODY, "vcpu": 8} + + created = client.post("/api/v1/vms", json=body, headers=headers) + assert created.status_code == 201 + assert ("create_vm", body) in service.calls + assert client.post("/api/v1/vms", json={**body, "nic_queues": 8}, + headers=headers).status_code == 422 + + +def test_rescue_iso_upload_enter_exit_and_safe_lifecycle(web): + client, _state, token, service, _manager, _seen = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + headers = {"X-CSRF-Token": csrf, "Content-Type": "application/octet-stream"} + json_headers = {"X-CSRF-Token": csrf} + assert client.get("/api/v1/rescue-templates").json() == {"templates": []} + + iso = bytearray(1024 * 1024) + for sector, kind in ((16, 1), (17, 0), (18, 255)): + offset = sector * 2048 + iso[offset] = kind + iso[offset + 1:offset + 6] = b"CD001" + iso[offset + 6] = 1 + iso[17 * 2048 + 7:17 * 2048 + 30] = b"EL TORITO SPECIFICATION" + iso[17 * 2048 + 71:17 * 2048 + 75] = (20).to_bytes(4, "little") + assert client.post("/api/v1/rescue-templates?name=Rescue", content=iso).status_code == 403 + invalid = client.post("/api/v1/rescue-templates?name=Invalid", + content=b"invalid", headers=headers) + assert invalid.status_code in (413, 422) + queued = client.post("/api/v1/rescue-templates?name=Rescue", + content=bytes(iso), headers=headers) + assert queued.status_code == 202, queued.text + import_job_id = queued.json()["job_id"] + for _ in range(100): + job = client.get(f"/api/v1/rescue-templates/import-jobs/{import_job_id}").json() + if job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert job["status"] == "completed", job + template = client.get("/api/v1/rescue-templates").json()["templates"][0] + assert template["name"] == "Rescue" + assert ("import_rescue_iso", template["volume_name"], len(iso)) in service.calls + + rescue_url = f"/api/v1/vms/{VM_ID}/rescue" + wrong = client.post(rescue_url, json={"template_id": template["id"], + "confirmation_name": "wrong"}, headers=json_headers) + assert wrong.status_code == 422 + started = client.post(rescue_url, json={"template_id": template["id"], + "confirmation_name": "alma-test"}, headers=json_headers) + assert started.status_code == 202, started.text + for _ in range(100): + rescue_job = client.get( + f"/api/v1/rescue-jobs/{started.json()['job_id']}").json() + if rescue_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert rescue_job["status"] == "completed", rescue_job + assert client.get(rescue_url).json()["active"] is True + assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"}, + headers=json_headers).status_code == 409 + assert client.delete(f"/api/v1/rescue-templates/{template['id']}", + headers=headers).status_code == 409 + + exited = client.post(f"{rescue_url}/exit", json={"confirmation_name": "alma-test"}, + headers=json_headers) + assert exited.status_code == 202, exited.text + for _ in range(100): + exit_job = client.get(f"/api/v1/rescue-jobs/{exited.json()['job_id']}").json() + if exit_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert exit_job["status"] == "completed", exit_job + assert client.get(rescue_url).json()["active"] is False + + # If a worker dies after saving its recovery record but the original + # persistent definition is still present, reading status safely clears + # the stale record and allows ordinary VM operations again. + restarted = client.post(rescue_url, json={"template_id": template["id"], + "confirmation_name": "alma-test"}, + headers=json_headers) + assert restarted.status_code == 202, restarted.text + for _ in range(100): + rescue_job = client.get( + f"/api/v1/rescue-jobs/{restarted.json()['job_id']}").json() + if rescue_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert rescue_job["status"] == "completed", rescue_job + service.vm["rescue_mode"] = False + service.vm["rescue_volume_name"] = None + assert client.get(rescue_url).json()["status"] is None + assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"}, + headers=json_headers).status_code == 200 + + # A staged rescue definition survives a graceful-shutdown timeout. The + # owner can power off and cold-start it, while reset/reboot stay blocked. + service.rescue_pending_manual_restart = True + staged_request = client.post(rescue_url, json={"template_id": template["id"], + "confirmation_name": "alma-test"}, + headers=json_headers) + assert staged_request.status_code == 202, staged_request.text + for _ in range(100): + staged_job = client.get( + f"/api/v1/rescue-jobs/{staged_request.json()['job_id']}").json() + if staged_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert staged_job["status"] == "completed", staged_job + assert staged_job["pending_manual_restart"] is True + staged_state = client.get(rescue_url).json() + assert staged_state["staged"] is True and staged_state["active"] is False + assert staged_state["can_exit"] is True + assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reset"}, + headers=json_headers).status_code == 409 + assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "poweroff"}, + headers=json_headers).status_code == 200 + assert client.get(rescue_url).json()["staged"] is True + assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "start"}, + headers=json_headers).status_code == 200 + assert client.get(rescue_url).json()["active"] is True + assert client.get(rescue_url).json()["staged"] is False + restored = client.post(f"{rescue_url}/exit", + json={"confirmation_name": "alma-test"}, headers=json_headers) + assert restored.status_code == 202, restored.text + for _ in range(100): + restored_job = client.get( + f"/api/v1/rescue-jobs/{restored.json()['job_id']}").json() + if restored_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert restored_job["status"] == "completed", restored_job + + staged_request = client.post(rescue_url, json={"template_id": template["id"], + "confirmation_name": "alma-test"}, + headers=json_headers) + assert staged_request.status_code == 202, staged_request.text + for _ in range(100): + staged_job = client.get( + f"/api/v1/rescue-jobs/{staged_request.json()['job_id']}").json() + if staged_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert staged_job["status"] == "completed", staged_job + force_url = f"{rescue_url}/force-start" + assert client.post(force_url, json={"confirmation_name": "alma-test"}, + headers=json_headers).status_code == 422 + assert client.post(force_url, + json={"confirmation_name": "wrong", "ack_data_loss": True}, + headers=json_headers).status_code == 422 + forced = client.post(force_url, + json={"confirmation_name": "alma-test", "ack_data_loss": True}, + headers=json_headers) + assert forced.status_code == 202, forced.text + for _ in range(100): + force_job = client.get( + f"/api/v1/rescue-jobs/{forced.json()['job_id']}").json() + if force_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert force_job["status"] == "completed", force_job + assert force_job["operation"] == "force" + assert client.get(rescue_url).json()["active"] is True + assert client.post(force_url, + json={"confirmation_name": "alma-test", "ack_data_loss": True}, + headers=json_headers).status_code == 409 + restored = client.post(f"{rescue_url}/exit", + json={"confirmation_name": "alma-test"}, headers=json_headers) + assert restored.status_code == 202, restored.text + for _ in range(100): + restored_job = client.get( + f"/api/v1/rescue-jobs/{restored.json()['job_id']}").json() + if restored_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert restored_job["status"] == "completed", restored_job + assert client.delete(f"/api/v1/rescue-templates/{template['id']}", + headers=headers).json() == {"deleted": True} + + +def test_orphan_rescue_marker_blocks_vm_actions_even_without_database_record(web): + client, _state, token, service, _manager, _seen = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + service.vm["rescue_mode"] = True + headers = {"X-CSRF-Token": csrf} + assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"}, + headers=headers).status_code == 409 + assert client.delete(f"/api/v1/vms/{VM_ID}", headers=headers).status_code == 409 + service.vm["rescue_mode"] = False + service.vm["rescue_staged"] = True + assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"}, + headers=headers).status_code == 409 + assert client.delete(f"/api/v1/vms/{VM_ID}", headers=headers).status_code == 409 + + +def test_orphan_staged_rescue_marker_blocks_reinstall(web): + client, _state, _token, service, _manager, _seen = web + csrf, template_id, _volume_name = configure_reinstall_case(web) + service.vm["rescue_staged"] = True + response = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={"template_id": template_id, "confirmation_name": "cloud-vm", + "root_password": GUEST_PASSWORD}, + headers={"X-CSRF-Token": csrf}, + ) + assert response.status_code == 409, response.text + + +def test_rescue_premount_failure_does_not_enable_force_restart(web): + client, _state, token, service, _manager, _seen = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + headers = {"X-CSRF-Token": csrf} + iso = bytearray(1024 * 1024) + for sector, kind in ((16, 1), (17, 0), (18, 255)): + offset = sector * 2048 + iso[offset] = kind + iso[offset + 1:offset + 6] = b"CD001" + iso[offset + 6] = 1 + iso[17 * 2048 + 7:17 * 2048 + 30] = b"EL TORITO SPECIFICATION" + iso[17 * 2048 + 71:17 * 2048 + 75] = (20).to_bytes(4, "little") + imported = client.post("/api/v1/rescue-templates?name=Rescue", + content=bytes(iso), headers=headers) + assert imported.status_code == 202, imported.text + for _ in range(100): + import_job = client.get( + f"/api/v1/rescue-templates/import-jobs/{imported.json()['job_id']}").json() + if import_job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert import_job["status"] == "completed", import_job + template = client.get("/api/v1/rescue-templates").json()["templates"][0] + service.rescue_enter_error = VMError( + "救援 ISO 预挂载失败,原虚拟机未受影响", 502) + started = client.post(f"/api/v1/vms/{VM_ID}/rescue", + json={"template_id": template["id"], + "confirmation_name": "alma-test"}, headers=headers) + assert started.status_code == 202, started.text + for _ in range(100): + job = client.get(f"/api/v1/rescue-jobs/{started.json()['job_id']}").json() + if job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert job["status"] == "failed", job + assert "救援 ISO 预挂载失败" in job["error"] + assert client.get(f"/api/v1/vms/{VM_ID}/rescue").json()["status"] is None + assert client.post(f"/api/v1/vms/{VM_ID}/rescue/force-start", + json={"confirmation_name": "alma-test", "ack_data_loss": True}, + headers=headers).status_code == 409 + assert client.post(f"/api/v1/vms/{VM_ID}/actions", + json={"action": "poweroff"}, headers=headers).status_code == 200 + + +def test_cloud_template_and_creation_routes_enforce_auth_csrf_and_fields(web): + client, _, token, service, _, _ = web + import_body = { + "name": "AlmaLinux 10 Generic Cloud", + "url": "https://example.invalid/AlmaLinux-10-GenericCloud.qcow2", + "sha256": "a" * 64, + } + assert client.get("/api/v1/vm-templates").status_code == 401 + assert client.post("/api/v1/vm-templates/import", json=import_body).status_code == 401 + assert client.post("/api/v1/vms", json=CLOUD_CREATE_BODY).status_code == 401 + + csrf = setup_admin(client, token) + configure_host(client, csrf) + assert client.get("/api/v1/vm-templates").json() == {"templates": []} + assert client.post("/api/v1/vm-templates/import", json=import_body).status_code == 403 + assert client.post("/api/v1/vms", json=CLOUD_CREATE_BODY).status_code == 403 + headers = {"X-CSRF-Token": csrf} + assert client.post("/api/v1/vm-templates/import", json={**import_body, "sha256": "bad"}, + headers=headers).status_code == 422 + assert client.post("/api/v1/vms", json={**CLOUD_CREATE_BODY, "source": "unknown"}, + headers=headers).status_code == 422 + assert client.post("/api/v1/vms", json={k: v for k, v in CLOUD_CREATE_BODY.items() + if k != "public_ip_cidr"}, + headers=headers).status_code == 422 + assert client.post("/api/v1/vms", json=CLOUD_CREATE_BODY, + headers=headers).status_code == 404 + assert not any(call[0] == "create_cloud_vm" for call in service.calls) + + +def test_cloud_template_import_job_and_create_dispatch(web): + client, state, token, service, manager, _ = web + csrf = setup_admin(client, token) + host_body = {**HOST_BODY, "default_network": "bridge:br0"} + assert client.put("/api/v1/host", json=host_body, + headers={"X-CSRF-Token": csrf}).status_code == 200 + service.calls.clear() + headers = {"X-CSRF-Token": csrf} + digest = "a" * 64 + image = state.data_dir / "verified-cloud.qcow2" + image.write_bytes(b"QFI\xfbverified test image") + with patch("virsh_panel.app.download_verified_image", + return_value=(image, 2 * 1024**3)): + queued = client.post("/api/v1/vm-templates/import", json={ + "name": "AlmaLinux 10", "url": OFFICIAL_CLOUD_URL, "sha256": digest, + }, headers=headers) + assert queued.status_code == 202 + job_id = queued.json()["job_id"] + assert queued.json()["status"] == "running" + job = wait_for_import_job(client, job_id) + + assert job["status"] == "completed" + scope = template_scope(manager.current()) + template_id = template_id_for(scope, digest) + volume_name = template_volume_name(template_id) + assert job["template"]["id"] == template_id + assert ("import_template", volume_name, 2 * 1024**3) in service.calls + for _ in range(100): + if not image.exists(): + break + time.sleep(0.01) + assert not image.exists() + listed = client.get("/api/v1/vm-templates") + assert listed.status_code == 200 + assert listed.json()["templates"][0]["id"] == template_id + assert "scope" not in listed.text + + cloud_body = {**CLOUD_CREATE_BODY, "template_id": template_id} + created = client.post("/api/v1/vms", json=cloud_body, headers=headers) + assert created.status_code == 201 + assert created.json()["name"] == "cloud-vm" + expected_spec = {key: value for key, value in cloud_body.items() + if key not in {"source", "template_id"}} + expected_spec["os_name"] = "AlmaLinux 10" + expected_spec["vm_uuid"] = created.json()["uuid"] + created_cloud_calls = [call for call in service.calls + if call[0] == "create_cloud_vm"] + assert len(created_cloud_calls) == 1 + _operation, actual_spec, actual_volume = created_cloud_calls[0] + assert actual_volume == volume_name + assert actual_spec["root_password_hash"].startswith("$6$") + assert {key: value for key, value in actual_spec.items() + if key != "root_password_hash"} == expected_spec + assert ("create_vm", expected_spec) not in service.calls + + +def test_almalinux_9_template_import_exposes_stable_version_and_prevents_duplicate_name(web): + client, state, token, service, manager, _ = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + headers = {"X-CSRF-Token": csrf} + image = state.data_dir / "alma9-verified.qcow2" + image.write_bytes(b"QFI\xfbverified test image") + digest = "b" * 64 + with patch("virsh_panel.app.download_verified_image", + return_value=(image, 2 * 1024**3)): + queued = client.post("/api/v1/vm-templates/import", json={ + "name": "AlmaLinux 9", "url": OFFICIAL_ALMA9_URL, "sha256": digest, + }, headers=headers) + assert queued.status_code == 202 + job = wait_for_import_job(client, queued.json()["job_id"]) + + assert job["status"] == "completed" + template_id = template_id_for(template_scope(manager.current()), digest, "9") + volume_name = template_volume_name(template_id) + template = job["template"] + assert template["id"] == template_id + assert template["volume_name"] == volume_name + assert template["os_family"] == "AlmaLinux" + assert template["os_version"] == "9" + assert ("import_template", volume_name, 2 * 1024**3) in service.calls + assert client.get("/api/v1/vm-templates").json()["templates"] == [template] + + duplicate = client.post("/api/v1/vm-templates/import", json={ + "name": "ALMALINUX 9", "url": OFFICIAL_ALMA9_URL, "sha256": "c" * 64, + }, headers=headers) + assert duplicate.status_code == 409 + assert len([call for call in service.calls if call[0] == "import_template"]) == 1 + + +def test_cloud_vm_root_login_supports_key_and_hashed_initial_password(web): + client, state, token, service, manager, _ = web + csrf = setup_admin(client, token) + host_body = {**HOST_BODY, "default_network": "bridge:br0"} + assert client.put("/api/v1/host", json=host_body, + headers={"X-CSRF-Token": csrf}).status_code == 200 + scope = template_scope(manager.current()) + template_id = template_id_for(scope, "c" * 64) + volume_name = template_volume_name(template_id) + TemplateStore(state.data_dir).add( + scope, {"id": template_id, "volume_name": volume_name}, + ) + headers = {"X-CSRF-Token": csrf} + service.calls.clear() + + key_body = {**CLOUD_CREATE_BODY, "template_id": template_id} + key_response = client.post("/api/v1/vms", json=key_body, headers=headers) + assert key_response.status_code == 201 + key_spec = service.calls[-1][1] + assert service.calls[-1][0] == "create_cloud_vm" + assert key_spec["guest_ssh_public_key"] == CLOUD_CREATE_BODY["guest_ssh_public_key"] + assert "root_password" not in key_spec + assert key_spec["root_password_hash"].startswith("$6$") + assert key_response.json()["login_name"] == "root" + assert key_response.json()["auth_mode"] == "ssh_key_password" + assert key_response.json()["password_available"] + key_uuid = key_response.json()["uuid"] + key_credential = client.post( + f"/api/v1/vms/{key_uuid}/credential", headers=headers, + ) + assert key_credential.headers["Cache-Control"] == "no-store" + generated_key_password = key_credential.json()["password"] + assert key_credential.json()["login_name"] == "root" + assert key_credential.json()["auth_mode"] == "ssh_key_password" + assert len(generated_key_password) >= 24 + assert re.search(r"[A-Z]", generated_key_password) + assert re.search(r"[a-z]", generated_key_password) + assert re.search(r"[^A-Za-z0-9]", generated_key_password) + from passlib.hash import sha512_crypt + assert sha512_crypt.verify(generated_key_password, key_spec["root_password_hash"]) + assert generated_key_password not in key_response.text + assert generated_key_password not in client.get("/api/v1/vms").text + assert generated_key_password not in repr(service.calls) + + both_body = {**key_body, "name": "key-password-vm", + "root_password": GUEST_PASSWORD} + both_response = client.post("/api/v1/vms", json=both_body, headers=headers) + assert both_response.status_code == 201 + both_spec = service.calls[-1][1] + assert both_spec["guest_ssh_public_key"] == CLOUD_CREATE_BODY["guest_ssh_public_key"] + assert both_spec["root_password_hash"].startswith("$6$") + assert GUEST_PASSWORD not in repr(service.calls) + assert both_response.json()["auth_mode"] == "ssh_key_password" + assert client.post( + f"/api/v1/vms/{both_response.json()['uuid']}/credential", headers=headers, + ).json()["password"] == GUEST_PASSWORD + + password_body = { + **key_body, "guest_ssh_public_key": "", "root_password": GUEST_PASSWORD, + } + password_response = client.post("/api/v1/vms", json=password_body, + headers=headers) + assert password_response.status_code == 201 + password_spec = service.calls[-1][1] + assert service.calls[-1][0] == "create_cloud_vm" + assert password_spec["guest_ssh_public_key"] == "" + assert password_spec["root_password_hash"].startswith("$6$") + assert "root_password" not in password_spec + assert GUEST_PASSWORD not in password_response.text + assert GUEST_PASSWORD not in repr(service.calls) + password_uuid = password_response.json()["uuid"] + assert password_response.json()["password_available"] + assert GUEST_PASSWORD not in client.get("/api/v1/vms").text + assert GUEST_PASSWORD not in client.get(f"/api/v1/vms/{password_uuid}").text + assert client.post(f"/api/v1/vms/{password_uuid}/credential").status_code == 403 + assert client.post( + f"/api/v1/vms/{password_uuid}/credential", headers=headers, + ).json() == { + "login_name": "root", "auth_mode": "password", "password": GUEST_PASSWORD, + } + original_generation = service.vm["credential_generation"] + service.vm["credential_generation"] = "new-system-seed.iso" + assert not client.get(f"/api/v1/vms/{password_uuid}").json()["password_available"] + assert client.post(f"/api/v1/vms/{password_uuid}/credential", + headers=headers).json()["password"] is None + service.vm["credential_generation"] = original_generation + + for invalid_body in ( + {**password_body, "root_password": "too-short"}, + {**password_body, "root_password": "X" * 129}, + {**key_body, "root_password": "alllowercase123!"}, + {**key_body, "root_password": "ALLUPPERCASE123!"}, + {**key_body, "root_password": "NoSymbolPassword123"}, + ): + rejected = client.post("/api/v1/vms", json=invalid_body, + headers=headers) + assert rejected.status_code == 422 + assert len([call for call in service.calls + if call[0] == "create_cloud_vm"]) == 3 + + no_credential = {**key_body, "guest_ssh_public_key": ""} + generated = client.post("/api/v1/vms", json=no_credential, + headers=headers) + assert generated.status_code == 201 + assert generated.json()["password_available"] + generated_password = client.post( + f"/api/v1/vms/{generated.json()['uuid']}/credential", headers=headers, + ).json()["password"] + assert len(generated_password) >= 24 + assert generated_password not in generated.text + assert generated_password not in client.get("/api/v1/vms").text + assert generated_password not in repr(service.calls) + assert len([call for call in service.calls + if call[0] == "create_cloud_vm"]) == 4 + assert client.delete( + f"/api/v1/vms/{generated.json()['uuid']}", headers=headers, + ).status_code == 200 + assert not client.get(f"/api/v1/vms/{generated.json()['uuid']}").json()["password_available"] + + +def test_unknown_vm_has_no_recoverable_password(web): + client, _state, token, service, _manager, _ = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + listed = client.get("/api/v1/vms") + assert listed.status_code == 200 + assert listed.json()["items"][0]["login_name"] is None + assert listed.json()["items"][0]["auth_mode"] == "unknown" + assert not listed.json()["items"][0]["password_available"] + assert client.post( + f"/api/v1/vms/{VM_ID}/credential", headers={"X-CSRF-Token": csrf}, + ).json()["password"] is None + service.vm.update({"managed": True, "os_source": "cloud_template"}) + old_cloud = client.get(f"/api/v1/vms/{VM_ID}").json() + assert old_cloud["login_name"] == "root" + assert old_cloud["auth_mode"] == "unknown" + assert not old_cloud["password_available"] + + +def test_reinstall_key_without_password_removes_old_password(web): + client, _state, _token, _service, _manager, _ = web + csrf, template_id, _volume_name = configure_reinstall_case(web) + headers = {"X-CSRF-Token": csrf} + password_job = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={"template_id": template_id, "confirmation_name": "cloud-vm", + "root_password": GUEST_PASSWORD}, headers=headers, + ) + assert password_job.status_code == 202 + assert wait_for_reinstall_job(client, password_job.json()["job_id"], csrf)["status"] == "succeeded" + assert client.post(f"/api/v1/vms/{VM_ID}/credential", + headers=headers).json()["password"] == GUEST_PASSWORD + key_job = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={"template_id": template_id, "confirmation_name": "cloud-vm", + "ssh_public_key": CLOUD_CREATE_BODY["guest_ssh_public_key"]}, headers=headers, + ) + assert key_job.status_code == 202 + completed = wait_for_reinstall_job(client, key_job.json()["job_id"], csrf) + assert completed["status"] == "succeeded" + assert "generated_password" not in completed + assert client.post(f"/api/v1/vms/{VM_ID}/credential", + headers=headers).json()["password"] is None + assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key" + deleted = client.delete(f"/api/v1/vms/{VM_ID}", headers=headers) + assert deleted.status_code == 200 + assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "unknown" + + +def test_reinstall_auto_password_job_ack_keeps_vm_credential(web): + client, state, _token, service, _manager, _ = web + csrf, template_id, volume_name = configure_reinstall_case(web) + headers = {"X-CSRF-Token": csrf} + body = {"template_id": template_id, "confirmation_name": "cloud-vm"} + + assert client.post(f"/api/v1/vms/{VM_ID}/reinstall", json=body).status_code == 403 + queued = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", json=body, headers=headers, + ) + assert queued.status_code == 202 + assert queued.json()["status"] == "queued" + assert "generated_password" not in queued.json() + job_id = queued.json()["job_id"] + assert client.get(f"/api/v1/reinstall-jobs/{job_id}").status_code == 403 + + completed = wait_for_reinstall_job(client, job_id, csrf) + assert completed["status"] == "succeeded" + generated_password = completed["generated_password"] + assert len(generated_password) >= 24 + assert completed["vm_id"] == VM_ID + service_calls = [call for call in service.calls if call[0] == "reinstall_cloud_vm"] + assert len(service_calls) == 1 + assert service_calls[0][1:4] == (VM_ID, volume_name, "") + assert service_calls[0][4].startswith("$6$") + assert service_calls[0][5] == "AlmaLinux 10" + assert generated_password not in repr(service.calls) + + second = client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers) + assert second.status_code == 200 + assert second.json()["status"] == "succeeded" + assert second.json()["generated_password"] == generated_password + ack_url = f"/api/v1/reinstall-jobs/{job_id}/ack-password" + assert client.post(ack_url).status_code == 403 + ack = client.post(ack_url, headers=headers) + assert ack.status_code == 200 + assert ack.json() == {"acknowledged": True} + assert client.post(ack_url, headers=headers).json() == {"acknowledged": True} + after_ack = client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers) + assert after_ack.status_code == 200 + assert "generated_password" not in after_ack.json() + assert generated_password not in after_ack.text + assert client.get(f"/api/v1/vms/{VM_ID}").json()["password_available"] + revealed = client.post(f"/api/v1/vms/{VM_ID}/credential", headers=headers) + assert revealed.json()["password"] == generated_password + for path in state.data_dir.rglob("*"): + if path.is_file(): + assert generated_password.encode() not in path.read_bytes() + + assert client.post("/api/v1/logout", headers=headers).status_code == 200 + assert client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers).status_code == 401 + assert client.post(ack_url, headers=headers).status_code == 401 + + +def test_reinstall_key_and_manual_password_has_no_generated_password(web): + client, _state, _token, service, _manager, _ = web + csrf, template_id, volume_name = configure_reinstall_case(web) + public_key = CLOUD_CREATE_BODY["guest_ssh_public_key"] + queued = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={"template_id": template_id, "confirmation_name": "cloud-vm", + "ssh_public_key": public_key, "root_password": GUEST_PASSWORD}, + headers={"X-CSRF-Token": csrf}, + ) + assert queued.status_code == 202 + completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf) + assert completed["status"] == "succeeded" + assert "generated_password" not in completed + assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key_password" + assert client.post(f"/api/v1/vms/{VM_ID}/credential", + headers={"X-CSRF-Token": csrf}).json()["password"] == GUEST_PASSWORD + reinstall_call = next(call for call in service.calls + if call[0] == "reinstall_cloud_vm") + assert reinstall_call[1:4] == (VM_ID, volume_name, public_key) + assert reinstall_call[4].startswith("$6$") + assert reinstall_call[5] == "AlmaLinux 10" + + +@pytest.mark.parametrize("weak_password", [ + "short-A!", "alllowercase123!", "ALLUPPERCASE123!", "NoSymbolPassword123", +]) +def test_reinstall_rejects_weak_manual_root_password(web, weak_password): + client, _state, _token, service, _manager, _ = web + csrf, template_id, _volume_name = configure_reinstall_case(web) + response = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={"template_id": template_id, "confirmation_name": "cloud-vm", + "ssh_public_key": CLOUD_CREATE_BODY["guest_ssh_public_key"], + "root_password": weak_password}, + headers={"X-CSRF-Token": csrf}, + ) + assert response.status_code == 422 + assert "初始 root 密码" in response.json()["detail"] + assert not any(call[0] == "reinstall_cloud_vm" for call in service.calls) + + +def test_reinstall_requires_exact_name_and_blocks_duplicate_or_lifecycle_actions(web): + client, _state, _token, service, _manager, _ = web + csrf, template_id, _volume_name = configure_reinstall_case(web) + headers = {"X-CSRF-Token": csrf} + body = {"template_id": template_id, "confirmation_name": "cloud-vm"} + wrong = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={**body, "confirmation_name": "wrong-vm"}, headers=headers, + ) + assert wrong.status_code == 422 + assert not any(call[0] == "reinstall_cloud_vm" for call in service.calls) + + service.reinstall_gate = threading.Event() + try: + queued = client.post(f"/api/v1/vms/{VM_ID}/reinstall", + json=body, headers=headers) + assert queued.status_code == 202 + assert service.reinstall_started.wait(timeout=2) + duplicate = client.post(f"/api/v1/vms/{VM_ID}/reinstall", + json=body, headers=headers) + assert duplicate.status_code == 409 + action = client.post(f"/api/v1/vms/{VM_ID}/actions", + json={"action": "shutdown"}, headers=headers) + assert action.status_code == 409 + deletion = client.delete(f"/api/v1/vms/{VM_ID}?delete_disks=true", + headers=headers) + assert deletion.status_code == 409 + finally: + service.reinstall_gate.set() + + completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf) + assert completed["status"] == "succeeded" + assert len([call for call in service.calls + if call[0] == "reinstall_cloud_vm"]) == 1 + + +def test_cloud_template_import_job_reports_failure_without_registering_template(web): + client, _, token, service, _, _ = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + headers = {"X-CSRF-Token": csrf} + with patch("virsh_panel.app.download_verified_image", + side_effect=TemplateError("云镜像 SHA-256 不匹配", 422)): + queued = client.post("/api/v1/vm-templates/import", json={ + "name": "AlmaLinux 10", "url": OFFICIAL_CLOUD_URL, + "sha256": "b" * 64, + }, headers=headers) + assert queued.status_code == 202 + job = wait_for_import_job(client, queued.json()["job_id"]) + + assert job["status"] == "failed" + assert "SHA-256" in job["error"] + assert client.get("/api/v1/vm-templates").json() == {"templates": []} + assert not any(call[0] == "import_template" for call in service.calls) + + +def test_static_assets_and_security_headers(web): + client, _, _, service, _, _ = web + page = client.get("/") + assert page.status_code == 200 and "text/html" in page.headers["content-type"] + assert page.headers["cache-control"] == "no-store" + assert "frame-ancestors 'none'" in page.headers["content-security-policy"] + script_url = re.search(r'src="(/static/app\.js\?v=[^"]+)"', page.text) + style_url = re.search(r'href="(/static/styles\.css\?v=[^"]+)"', page.text) + assert script_url is not None and style_url is not None + script = client.get(script_url.group(1)) + style = client.get(style_url.group(1)) + assert script.status_code == 200 and script.headers["cache-control"] == "no-store" + assert style.status_code == 200 and style.headers["cache-control"] == "no-store" + assert "function updateCreateSource()" in script.text + assert ".create-source-picker" in style.text + assert client.get("/vendor/novnc/core/rfb.js").status_code == 200 + assert service.calls == [] + + +def test_non_loopback_plain_http_is_rejected(web): + client, *_ = web + with TestClient(client.app, base_url="http://panel.example.test") as insecure: + response = insecure.get("/api/v1/health") + assert response.status_code == 400 + assert response.json() == {"error": "请使用 HTTPS 访问面板"} + + +def test_plain_loopback_only_exposes_health(web): + client, _, token, *_ = web + with TestClient(client.app, base_url="http://127.0.0.1:8000", + client=("127.0.0.1", 50000)) as local: + assert local.get("/api/v1/health").json() == {"status": "ok"} + assert local.get("/").status_code == 400 + assert local.get("/api/v1/setup/status").status_code == 400 + assert local.post("/api/v1/setup/admin", json={ + "token": token, "username": "admin", "password": PASSWORD, + }).status_code == 400 + + +def test_trusted_local_reverse_proxy_https_and_websocket(web): + client, _, token, service, manager, _ = web + app = ProxyHeadersMiddleware(client.app, trusted_hosts=["127.0.0.1"]) + proxy_headers = { + "host": "panel.example.test", + "x-forwarded-proto": "https", + "x-forwarded-for": "198.51.100.100", + } + with TestClient(app, base_url="http://panel.example.test", + client=("127.0.0.1", 50000)) as proxy: + assert proxy.get("/api/v1/health", headers=proxy_headers).status_code == 200 + assert proxy.get("/api/v1/health", headers={"host": "panel.example.test"}).status_code == 400 + setup = proxy.post("/api/v1/setup/admin", json={ + "token": token, "username": "admin", "password": PASSWORD, + }, headers=proxy_headers) + assert setup.status_code == 200 + assert "secure" in setup.headers["set-cookie"].lower() + csrf = setup.json()["csrf_token"] + cookie = f"virsh_panel_session={proxy.cookies['virsh_panel_session']}" + save = proxy.put("/api/v1/host", json=HOST_BODY, headers={ + **proxy_headers, "X-CSRF-Token": csrf, "cookie": cookie, + }) + assert save.status_code == 200 + assert save.json()["configured"] is True + service.calls.clear() + with patch("virsh_panel.app.relay_console", new_callable=AsyncMock) as relay: + with proxy.websocket_connect( + f"ws://panel.example.test/api/v1/vms/{VM_ID}/console", + headers={**proxy_headers, "origin": ORIGIN, "cookie": cookie}, + ): + pass + assert service.calls == [("console_port", VM_ID)] + relay.assert_awaited_once() + with pytest.raises(WebSocketDisconnect) as plain_ws: + with proxy.websocket_connect( + f"ws://panel.example.test/api/v1/vms/{VM_ID}/console", + headers={"host": "panel.example.test", "origin": ORIGIN, "cookie": cookie}, + ): + pass + assert plain_ws.value.code == 4403 + assert manager.current() is not None + + +def test_untrusted_forwarded_proto_and_spoofed_local_host_are_rejected(web): + client, *_ = web + app = ProxyHeadersMiddleware(client.app, trusted_hosts=["127.0.0.1"]) + with TestClient(app, base_url="http://panel.example.test", + client=("198.51.100.10", 50000)) as direct: + spoofed_https = direct.get("/api/v1/health", headers={ + "host": "panel.example.test", "x-forwarded-proto": "https", + }) + spoofed_local_host = direct.get("/api/v1/health", headers={ + "host": "localhost", "x-forwarded-proto": "http", + }) + with pytest.raises(WebSocketDisconnect) as spoofed_ws: + with direct.websocket_connect( + f"ws://panel.example.test/api/v1/vms/{VM_ID}/console", + headers={"host": "panel.example.test", "origin": ORIGIN, + "x-forwarded-proto": "https"}, + ): + pass + assert spoofed_https.status_code == 400 + assert spoofed_local_host.status_code == 400 + assert spoofed_ws.value.code == 4403 + + +def test_websocket_origin_auth_and_console_relay(web): + client, _, token, service, _, _ = web + with pytest.raises(WebSocketDisconnect) as unauthenticated: + with client.websocket_connect( + f"wss://panel.example.test/api/v1/vms/{VM_ID}/console", + headers={"origin": ORIGIN, "host": "panel.example.test"}, + ): + pass + assert unauthenticated.value.code == 4401 + + csrf = setup_admin(client, token) + configure_host(client, csrf) + service.calls.clear() + cookie = f"virsh_panel_session={client.cookies['virsh_panel_session']}" + with pytest.raises(WebSocketDisconnect) as wrong_origin: + with client.websocket_connect( + f"wss://panel.example.test/api/v1/vms/{VM_ID}/console", + headers={"origin": "https://attacker.example", "cookie": cookie, + "host": "panel.example.test"}, + ): + pass + assert wrong_origin.value.code == 4403 + with patch("virsh_panel.app.relay_console", new_callable=AsyncMock) as relay: + with client.websocket_connect( + f"wss://panel.example.test/api/v1/vms/{VM_ID}/console", + headers={"origin": ORIGIN, "cookie": cookie, "host": "panel.example.test"}, + ): + pass + assert service.calls == [("console_port", VM_ID)] + relay.assert_awaited_once() + assert relay.await_args.kwargs["port"] == 5907 + assert relay.await_args.kwargs["ssh_target"] == "vp-managed" + assert relay.await_args.kwargs["ssh_config_file"] == "/fake/config" + + +def test_vm_metrics_requires_auth_validates_vm_and_isolates_host(tmp_path): + state = PanelState(tmp_path / "panel-data") + manager = FakeRemoteManager() + service = FakeVMService() + + class FakeMetricStore: + def __init__(self): + self.calls = [] + self.allowed_scope = None + + def query_metric_samples(self, scope, vm_id, **kwargs): + self.calls.append((scope, vm_id, kwargs)) + if scope != self.allowed_scope: + return [] + return [{"timestamp": 2_999_900, "cpu_percent": 25, + "memory_used_mib": None, "memory_total_mib": None, + "disk_read_bps": 128, "disk_write_bps": 0, + "network_rx_bps": 4096, "network_tx_bps": 1024}] + + metric_store = FakeMetricStore() + app = create_app(Settings(data_dir=state.data_dir, static_dir=STATIC_DIR), + panel_state=state, remote_manager=manager, + service_factory=lambda _profile: service, + metric_store=metric_store) + with TestClient(app, base_url=ORIGIN) as client: + endpoint = f"/api/v1/vms/{VM_ID}/metrics" + assert client.get(endpoint).status_code == 401 + token = state.token_file.read_text(encoding="ascii").strip() + csrf = setup_admin(client, token) + configure_host(client, csrf) + metric_store.allowed_scope = host_scope(manager.current()) + with patch("virsh_panel.app.time.time", return_value=3_000_000): + response = client.get(endpoint + "?range=30d") + assert response.status_code == 200 + body = response.json() + assert body["vm_id"] == VM_ID + assert body["range"] == "30d" + assert body["interval_seconds"] == query_interval_seconds(30 * 24 * 3600) + assert len(body["points"]) == 1 + scope, vm_id, args = metric_store.calls[-1] + assert scope == metric_store.allowed_scope and vm_id == VM_ID + assert args["since"] == 3_000_000 - 30 * 24 * 3600 + assert args["until"] == 3_000_000 and args["limit"] == 600 + + assert client.get(endpoint + "?range=60d").status_code == 422 + assert client.get("/api/v1/vms/not-a-uuid/metrics").status_code == 400 + assert client.get( + "/api/v1/vms/00000000-0000-4000-8000-000000000002/metrics" + ).status_code == 404 + before = len(metric_store.calls) + manager.profile["fingerprint"] = "SHA256:another-host" + with patch("virsh_panel.app.time.time", return_value=3_000_000): + changed_host = client.get(endpoint) + assert changed_host.status_code == 200 + assert changed_host.json()["points"] == [] + assert len(metric_store.calls) == before + 1 diff --git a/engine/tests/test_auth_sessions.py b/engine/tests/test_auth_sessions.py new file mode 100644 index 00000000..c3869c9a --- /dev/null +++ b/engine/tests/test_auth_sessions.py @@ -0,0 +1,79 @@ +"""Database sessions bind to immutable user IDs, not reusable usernames.""" + +from __future__ import annotations + +import json +import time + +import pytest + +from virsh_panel.auth import DatabaseSessionStore, SessionStore + + +class _Records: + def __init__(self): + self.values = {} + + def get(self, record_type, record_key): + return self.values.get((record_type, record_key)) + + def set(self, record_type, record_key, value): + self.values[(record_type, record_key)] = value + + def delete(self, record_type, record_key): + self.values.pop((record_type, record_key), None) + + +def test_database_session_round_trips_immutable_user_id(): + records = _Records() + sessions = DatabaseSessionStore(records) + created = sessions.issue("operator", user_id=47) + assert created.user_id == 47 + key = sessions._key(created.token) + payload = json.loads(records.get("session", key)) + assert payload["user_id"] == 47 + assert created.token not in records.get("session", key) + restored = DatabaseSessionStore(records).get(created.token) + assert restored == created + + +@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0]) +def test_database_session_issue_refuses_missing_or_invalid_user_id(invalid_id): + sessions = DatabaseSessionStore(_Records()) + with pytest.raises(ValueError, match="positive user ID"): + sessions.issue("operator", user_id=invalid_id) + + +@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0]) +def test_database_session_get_rejects_legacy_or_invalid_id(invalid_id): + records = _Records() + sessions = DatabaseSessionStore(records) + token = "legacy-token" + payload = { + "username": "operator", "csrf_token": "csrf-token", + "expires_at": time.time() + 100, + } + if invalid_id is not None: + payload["user_id"] = invalid_id + records.set("session", sessions._key(token), json.dumps(payload)) + assert sessions.get(token) is None + + +def test_database_session_expired_token_is_removed(): + records = _Records() + sessions = DatabaseSessionStore(records) + token = "expired-token" + key = sessions._key(token) + records.set("session", key, json.dumps({ + "username": "operator", "user_id": 47, + "csrf_token": "csrf-token", "expires_at": time.time() - 1, + })) + assert sessions.get(token) is None + assert records.get("session", key) is None + + +def test_injected_memory_sessions_keep_username_only_compatibility(): + sessions = SessionStore() + created = sessions.issue("test-admin") + assert created.user_id is None + assert sessions.get(created.token) == created diff --git a/engine/tests/test_cloud_init.py b/engine/tests/test_cloud_init.py new file mode 100644 index 00000000..e2b2f82d --- /dev/null +++ b/engine/tests/test_cloud_init.py @@ -0,0 +1,230 @@ +"""Cloud-init public networking and NoCloud seed behavior.""" + +from __future__ import annotations + +import importlib.util +import json +import uuid + +import pytest + +from virsh_panel.cloud_init import ( + build_seed_iso, generate_root_password, hash_root_password, read_seed_network, + validate_cloud_network, +) + + +PUBLIC_KEY = ( + "ssh-ed25519 " + "AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 " + "panel-test" +) +GUEST_PASSWORD = "A-strong-guest-password-2026" + + +def _user_data(seed: bytes) -> dict: + """Read the single-line JSON cloud-config embedded in the generated ISO.""" + prefix = b"#cloud-config\n" + start = seed.index(prefix) + len(prefix) + return json.loads(seed[start:seed.index(b"\n", start)]) + + +@pytest.mark.parametrize( + ("address", "gateway"), + [ + ("8.8.8.18/24", "8.8.8.1"), + ("8.8.8.18/28", "8.8.8.17"), + ("123.123.123.114/24", "123.123.123.113"), + ], +) +def test_public_network_accepts_24_and_28(address, gateway): + validated = validate_cloud_network( + address, gateway, ["1.1.1.1", "8.8.8.8"], PUBLIC_KEY, + ) + assert validated == { + "public_ip_cidr": address, + "gateway": gateway, + "dns_servers": ["1.1.1.1", "8.8.8.8"], + "guest_ssh_public_key": PUBLIC_KEY, + } + + +def test_cloud_login_accepts_key_and_root_password_together(): + network = ("8.8.8.18/24", "8.8.8.1", ["1.1.1.1"]) + password_hash = hash_root_password(GUEST_PASSWORD) + assert password_hash.startswith("$6$") + assert GUEST_PASSWORD not in password_hash + assert hash_root_password(GUEST_PASSWORD) != password_hash + + validated = validate_cloud_network( + *network, "", root_password_hash=password_hash, + ) + assert validated["root_password_hash"] == password_hash + assert not validated["guest_ssh_public_key"] + + together = validate_cloud_network( + *network, PUBLIC_KEY, root_password_hash=password_hash, + ) + assert together["guest_ssh_public_key"] == PUBLIC_KEY + assert together["root_password_hash"] == password_hash + + with pytest.raises(ValueError): + validate_cloud_network(*network, "", root_password_hash=None) + with pytest.raises(ValueError): + validate_cloud_network(*network, "", root_password_hash=GUEST_PASSWORD) + + +@pytest.mark.parametrize("invalid", [ + "Short1!", "alllowercase12!", "ALLUPPERCASE12!", "NoSymbolPassword12", + "A-lowercase\npassword12", "A-lowercase-password-" + "x" * 110, +]) +def test_manual_root_password_requires_length_case_and_symbol(invalid): + with pytest.raises(ValueError, match="初始 root 密码"): + hash_root_password(invalid) + + +def test_generated_root_password_always_meets_policy(): + samples = set() + for _ in range(50): + password = generate_root_password() + samples.add(password) + assert len(password) == 32 + assert any(char.isupper() for char in password) + assert any(char.islower() for char in password) + assert any(not char.isalnum() for char in password) + assert len(samples) == 50 + assert hash_root_password(password).startswith("$6$") + + +@pytest.mark.parametrize( + ("address", "gateway"), + [ + ("192.168.1.18/24", "192.168.1.1"), + ("10.0.0.18/24", "10.0.0.1"), + ("172.16.0.18/24", "172.16.0.1"), + ("127.0.0.18/24", "127.0.0.1"), + ("169.254.0.18/24", "169.254.0.1"), + ("224.0.0.18/24", "224.0.0.1"), + ("2001:4860:4860::8888/64", "2001:4860:4860::1"), + ("8.8.8.0/24", "8.8.8.1"), + ("8.8.8.255/24", "8.8.8.1"), + ("8.8.8.18/28", "8.8.8.1"), + ("8.8.8.18", "8.8.8.1"), + ], +) +def test_public_network_rejects_nonpublic_or_unroutable_pairs(address, gateway): + with pytest.raises(ValueError): + validate_cloud_network(address, gateway, ["1.1.1.1"], PUBLIC_KEY) + + +@pytest.mark.parametrize( + ("dns", "key"), + [ + (["not-an-ip"], PUBLIC_KEY), + (["192.168.1.1"], PUBLIC_KEY), + ([], PUBLIC_KEY), + (["1.1.1.1"], "not-an-ssh-key"), + (["1.1.1.1"], PUBLIC_KEY + "\nruncmd: [evil]"), + ], +) +def test_public_network_rejects_bad_dns_and_ssh_key(dns, key): + with pytest.raises(ValueError): + validate_cloud_network("8.8.8.18/24", "8.8.8.1", dns, key) + + +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_seed_iso_has_nocloud_files_and_mac_specific_static_network(): + vm_uuid = str(uuid.uuid4()) + mac = "52:54:00:12:34:56" + validated = validate_cloud_network( + "8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY, + ) + seed = build_seed_iso(vm_uuid, "cloud-vm", mac, validated) + + assert isinstance(seed, bytes) + assert seed[32769:32774] == b"CD001" # ISO-9660 primary volume descriptor + assert b"CIDATA" in seed + for marker in ( + b"user-data", b"meta-data", b"network-config", b"8.8.8.18/28", + b"8.8.8.17", b"1.1.1.1", mac.encode(), PUBLIC_KEY.encode(), + ): + assert marker in seed + assert b'"routes": [{"to": "0.0.0.0/0", "via": "8.8.8.17"}]' in seed + assert b'"to": "default"' not in seed + user_data = _user_data(seed) + assert user_data["disable_root"] is False + assert user_data["ssh_pwauth"] is False + assert user_data["users"][0]["name"] == "root" + assert user_data["users"][0]["ssh_authorized_keys"] == [PUBLIC_KEY] + assert "hashed_passwd" not in user_data["users"][0] + assert "passwd" not in user_data["users"][0] + sshd_dropin = user_data["write_files"][0] + assert sshd_dropin["path"] == "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf" + assert "PermitRootLogin prohibit-password" in sshd_dropin["content"] + assert "PasswordAuthentication no" in sshd_dropin["content"] + assert b"almalinux" not in seed + assert read_seed_network(seed) == { + "public_ip_cidr": "8.8.8.18/28", + "gateway": "8.8.8.17", + "dns_servers": ["1.1.1.1"], + "mac": mac, + } + + +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_read_seed_network_rejects_invalid_iso_without_exposing_credentials(): + with pytest.raises(ValueError): + read_seed_network(b"not an ISO") + with pytest.raises(ValueError): + read_seed_network(b"x" * (1024 * 1024 + 1)) + + +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_password_seed_sets_root_hash_and_enables_ssh_password_login(): + password_hash = hash_root_password(GUEST_PASSWORD) + validated = validate_cloud_network( + "8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], "", + root_password_hash=password_hash, + ) + seed = build_seed_iso( + str(uuid.uuid4()), "password-vm", "52:54:00:12:34:56", validated, + ) + user_data = _user_data(seed) + + assert user_data["disable_root"] is False + assert user_data["ssh_pwauth"] is True + assert user_data["users"][0]["name"] == "root" + assert user_data["users"][0]["lock_passwd"] is False + assert user_data["users"][0]["hashed_passwd"] == password_hash + assert "ssh_authorized_keys" not in user_data["users"][0] + sshd_dropin = user_data["write_files"][0] + assert sshd_dropin["path"] == "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf" + assert "PermitRootLogin yes" in sshd_dropin["content"] + assert "PasswordAuthentication yes" in sshd_dropin["content"] + assert GUEST_PASSWORD.encode() not in seed + + +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_seed_allows_root_password_and_ssh_key_together(): + password_hash = hash_root_password(GUEST_PASSWORD) + validated = validate_cloud_network( + "8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY, + root_password_hash=password_hash, + ) + seed = build_seed_iso( + str(uuid.uuid4()), "both-vm", "52:54:00:12:34:56", validated, + ) + user_data = _user_data(seed) + root = user_data["users"][0] + assert root["name"] == "root" + assert root["lock_passwd"] is False + assert root["ssh_authorized_keys"] == [PUBLIC_KEY] + assert root["hashed_passwd"] == password_hash + assert user_data["ssh_pwauth"] is True + assert "PermitRootLogin yes" in user_data["write_files"][0]["content"] + assert "PasswordAuthentication yes" in user_data["write_files"][0]["content"] + assert GUEST_PASSWORD.encode() not in seed diff --git a/engine/tests/test_cloud_templates.py b/engine/tests/test_cloud_templates.py new file mode 100644 index 00000000..9b060298 --- /dev/null +++ b/engine/tests/test_cloud_templates.py @@ -0,0 +1,181 @@ +"""Official-image import restrictions and private template catalog tests.""" + +from __future__ import annotations + +import hashlib +import io +import stat +import struct +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +from virsh_panel.cloud_templates import ( + TemplateError, + TemplateStore, + _RejectRedirects, + download_verified_image, + image_version_for, + template_id_for, + template_scope, + template_volume_name, + validate_image_url, +) + + +OFFICIAL = ( + "https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/" + "AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2" +) +OFFICIAL_9 = ( + "https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/" + "AlmaLinux-9-GenericCloud-latest.x86_64.qcow2" +) + + +def test_official_almalinux_9_and_10_are_distinct_supported_versions(): + assert validate_image_url(OFFICIAL_9) == OFFICIAL_9 + assert image_version_for(OFFICIAL_9) == "9" + assert image_version_for(OFFICIAL) == "10" + scope = "a" * 64 + digest = "b" * 64 + assert template_id_for(scope, digest, "9").startswith("alma9-") + assert template_id_for(scope, digest, "10").startswith("alma10-") + assert template_volume_name(template_id_for(scope, digest, "9")).startswith( + "panel-template-alma9-" + ) + with pytest.raises(TemplateError): + validate_image_url(OFFICIAL_9.replace("/almalinux/9/", "/almalinux/10/")) + with pytest.raises(TemplateError): + validate_image_url(OFFICIAL_9.replace("AlmaLinux-9-", "AlmaLinux-8-")) + with pytest.raises(TemplateError): + template_id_for(scope, digest, "8") + + +def qcow2_fixture(virtual_size=2 * 1024**3) -> bytes: + header = bytearray(104) + header[:4] = b"QFI\xfb" + header[4:8] = struct.pack(">I", 3) + header[20:24] = struct.pack(">I", 16) + header[24:32] = struct.pack(">Q", virtual_size) + header[100:104] = struct.pack(">I", 104) + return bytes(header) + b"fake qcow2 content for controlled import test" + + +@pytest.mark.parametrize( + "url", + [ + "http://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2", + "https://evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2", + "https://repo.almalinux.org.evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2", + "https://user:pass@repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2", + "https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/../../etc/passwd", + "https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2?token=secret", + ], +) +def test_import_url_rejects_nonofficial_and_ambiguous_targets(url): + with pytest.raises(TemplateError): + validate_image_url(url) + + +def test_verified_image_is_private_and_has_expected_virtual_size(tmp_path): + body = qcow2_fixture() + digest = hashlib.sha256(body).hexdigest() + opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body)) + with patch("virsh_panel.cloud_templates.urllib.request.build_opener", + return_value=opener): + downloaded, virtual_size = download_verified_image(OFFICIAL, digest, tmp_path) + try: + assert downloaded.read_bytes() == body + assert virtual_size == 2 * 1024**3 + assert stat.S_IMODE(downloaded.stat().st_mode) == 0o600 + finally: + downloaded.unlink() + + +def test_failed_hash_never_leaves_unverified_template_file(tmp_path): + body = qcow2_fixture() + opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body)) + with patch("virsh_panel.cloud_templates.urllib.request.build_opener", + return_value=opener): + with pytest.raises(TemplateError, match="SHA-256"): + download_verified_image(OFFICIAL, "0" * 64, tmp_path) + assert list(tmp_path.iterdir()) == [] + + +def test_redirect_to_nonofficial_target_is_rejected_before_following(): + handler = _RejectRedirects() + with pytest.raises(TemplateError, match="重定向"): + handler.redirect_request(None, None, 302, "Found", {}, + "http://127.0.0.1/private") + + +def test_external_data_file_feature_is_rejected(tmp_path): + body = bytearray(qcow2_fixture()) + body[72:80] = struct.pack(">Q", 4) + digest = hashlib.sha256(body).hexdigest() + opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body)) + with patch("virsh_panel.cloud_templates.urllib.request.build_opener", + return_value=opener): + with pytest.raises(TemplateError, match="外部依赖"): + download_verified_image(OFFICIAL, digest, tmp_path) + assert list(tmp_path.iterdir()) == [] + + +def test_template_catalog_is_private_and_scoped_to_host_and_disk_pool(tmp_path): + data_dir = tmp_path / "data" + data_dir.mkdir(mode=0o700) + store = TemplateStore(data_dir) + profile = { + "host": "hypervisor.example", "port": 2222, + "fingerprint": "SHA256:fixture", "storage_pool": "/home/kvm", + } + scope = template_scope(profile) + other_scope = template_scope({**profile, "storage_pool": "/other/pool"}) + record = { + "id": "alma10-example", "name": "AlmaLinux 10", "sha256": "a" * 64, + "volume_name": "alma10-cloud.qcow2", "virtual_size": 2 * 1024**3, + } + assert store.add(scope, record) == record + assert store.list(scope) == [record] + assert store.list(other_scope) == [] + assert TemplateStore(data_dir).get(scope, record["id"]) == record + assert stat.S_IMODE(store.file.stat().st_mode) == 0o600 + with pytest.raises(TemplateError): + store.get(other_scope, record["id"]) + with pytest.raises(TemplateError): + store.add(scope, record) + + +def test_template_rename_preserves_image_record_and_host_scope(tmp_path): + data_dir = tmp_path / "data" + data_dir.mkdir(mode=0o700) + store = TemplateStore(data_dir) + scope = "a" * 64 + other_scope = "b" * 64 + template_id = template_id_for(scope, "c" * 64, "9") + record = { + "id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux", + "os_version": "9", "sha256": "c" * 64, + "volume_name": template_volume_name(template_id), "virtual_size": 2 * 1024**3, + } + store.add(scope, record) + store.add(scope, {**record, "id": "other", "name": "Another name"}) + store.add(other_scope, {**record, "name": "Other host"}) + + with pytest.raises(TemplateError) as inaccessible: + store.rename(other_scope, "other", "Missing") + assert inaccessible.value.status == 404 + with pytest.raises(TemplateError) as duplicate: + store.rename(scope, template_id, "another NAME") + assert duplicate.value.status == 409 + for invalid in ("", "x" * 65, "bad\x7fentry"): + with pytest.raises(TemplateError): + store.rename(scope, template_id, invalid) + + updated = store.rename(scope, template_id, " 新名称 ") + assert updated == {**record, "name": "新名称"} + assert TemplateStore(data_dir).get(scope, template_id) == updated + assert store.get(other_scope, template_id)["name"] == "Other host" + assert stat.S_IMODE(store.file.stat().st_mode) == 0o600 diff --git a/engine/tests/test_config.py b/engine/tests/test_config.py new file mode 100644 index 00000000..7705d0e5 --- /dev/null +++ b/engine/tests/test_config.py @@ -0,0 +1,31 @@ +"""The panel starts without a prefilled host or administrator config file.""" + +from dataclasses import replace +from pathlib import Path + +import pytest + +from virsh_panel.config import PROJECT_DIR, Settings + + +def test_default_data_directory_stays_inside_project(monkeypatch): + monkeypatch.delenv("PANEL_DATA_DIR", raising=False) + assert Settings.from_env().data_dir == PROJECT_DIR / "data" + + +def test_runtime_settings_require_no_host_or_admin_values(tmp_path): + settings = Settings(data_dir=tmp_path) + settings.validate() + assert settings.secure_cookie is True + assert settings.ssh_binary == "ssh" + + +@pytest.mark.parametrize("bad_path", [Path("relative/data"), Path("/")]) +def test_rejects_unsafe_data_directory(bad_path): + with pytest.raises(ValueError): + replace(Settings(), data_dir=bad_path).validate() + + +def test_rejects_missing_static_assets(tmp_path): + with pytest.raises(ValueError): + replace(Settings(), static_dir=tmp_path / "missing").validate() diff --git a/engine/tests/test_console.py b/engine/tests/test_console.py new file mode 100644 index 00000000..144db610 --- /dev/null +++ b/engine/tests/test_console.py @@ -0,0 +1,199 @@ +"""Focused tests for the SSH backed browser console stream.""" + +from __future__ import annotations + +import asyncio +import unittest +from unittest.mock import AsyncMock, patch + +from virsh_panel.console import ConsoleRelayError, WebSocketDisconnect, relay_console + + +class FakeStdin: + def __init__(self) -> None: + self.data = bytearray() + self.written = asyncio.Event() + self.closed = False + + def write(self, data: bytes) -> None: + self.data.extend(data) + self.written.set() + + async def drain(self) -> None: + await asyncio.sleep(0) + + def close(self) -> None: + self.closed = True + + +class FakeProcess: + def __init__(self) -> None: + self.stdin = FakeStdin() + self.stdout = asyncio.StreamReader() + self.returncode: int | None = None + self.exited = asyncio.Event() + self.terminated = False + self.killed = False + + async def wait(self) -> int: + await self.exited.wait() + assert self.returncode is not None + return self.returncode + + def finish(self, code: int) -> None: + self.returncode = code + self.exited.set() + self.stdout.feed_eof() + + def terminate(self) -> None: + self.terminated = True + self.finish(-15) + + def kill(self) -> None: + self.killed = True + self.finish(-9) + + +class FakeWebSocket: + def __init__(self) -> None: + self.incoming: asyncio.Queue[dict[str, object]] = asyncio.Queue() + self.sent: list[bytes] = [] + self.sent_event = asyncio.Event() + + async def receive(self) -> dict[str, object]: + return await self.incoming.get() + + async def send_bytes(self, data: bytes) -> None: + self.sent.append(data) + self.sent_event.set() + + +class RelayConsoleTests(unittest.IsolatedAsyncioTestCase): + async def test_relay_binary_frames_and_disconnect_cleans_up(self) -> None: + process = FakeProcess() + websocket = FakeWebSocket() + spawn = AsyncMock(return_value=process) + with patch("virsh_panel.console.asyncio.create_subprocess_exec", spawn): + running = asyncio.create_task( + relay_console( + websocket, + port=5901, + ssh_target="operator@hypervisor.example", + known_hosts_file="/home/virsh-panel/data/current/known_hosts", + ssh_config_file="/home/virsh-panel/data/current/config", + ) + ) + process.stdout.feed_data(b"RFB 003.008\n") + await asyncio.wait_for(websocket.sent_event.wait(), 1) + await websocket.incoming.put( + {"type": "websocket.receive", "bytes": b"client bytes"} + ) + await asyncio.wait_for(process.stdin.written.wait(), 1) + await websocket.incoming.put({"type": "websocket.disconnect"}) + await asyncio.wait_for(running, 1) + + self.assertEqual(websocket.sent, [b"RFB 003.008\n"]) + self.assertEqual(bytes(process.stdin.data), b"client bytes") + self.assertTrue(process.stdin.closed) + self.assertTrue(process.terminated) + command = spawn.await_args.args + self.assertEqual(command[0], "ssh") + self.assertEqual(command[1:3], ("-F", "/home/virsh-panel/data/current/config")) + self.assertIn("BatchMode=yes", command) + self.assertIn("StrictHostKeyChecking=yes", command) + self.assertIn("UserKnownHostsFile=/home/virsh-panel/data/current/known_hosts", command) + self.assertEqual(command[-3:], ("-W", "127.0.0.1:5901", "operator@hypervisor.example")) + self.assertEqual(spawn.await_args.kwargs["stderr"], asyncio.subprocess.DEVNULL) + + async def test_ssh_failure_is_reported(self) -> None: + process = FakeProcess() + process.finish(255) + websocket = FakeWebSocket() + with patch( + "virsh_panel.console.asyncio.create_subprocess_exec", + AsyncMock(return_value=process), + ): + with self.assertRaisesRegex(ConsoleRelayError, "status 255"): + await relay_console(websocket, port=5900, ssh_target="host.example") + self.assertTrue(process.stdin.closed) + self.assertFalse(process.terminated) + + async def test_cancellation_terminates_ssh(self) -> None: + process = FakeProcess() + websocket = FakeWebSocket() + spawn = AsyncMock(return_value=process) + with patch("virsh_panel.console.asyncio.create_subprocess_exec", spawn): + running = asyncio.create_task( + relay_console(websocket, port=5900, ssh_target="host.example") + ) + for _ in range(10): + if spawn.await_count: + break + await asyncio.sleep(0) + running.cancel() + with self.assertRaises(asyncio.CancelledError): + await running + self.assertTrue(process.stdin.closed) + self.assertTrue(process.terminated) + + async def test_rejects_text_frames(self) -> None: + process = FakeProcess() + websocket = FakeWebSocket() + await websocket.incoming.put({"type": "websocket.receive", "text": "hello"}) + with patch( + "virsh_panel.console.asyncio.create_subprocess_exec", + AsyncMock(return_value=process), + ): + with self.assertRaisesRegex(ConsoleRelayError, "binary"): + await relay_console(websocket, port=5900, ssh_target="host.example") + self.assertTrue(process.terminated) + + async def test_send_disconnect_terminates_ssh(self) -> None: + class DisconnectingWebSocket(FakeWebSocket): + async def send_bytes(self, data: bytes) -> None: + raise WebSocketDisconnect(1006) + + process = FakeProcess() + process.stdout.feed_data(b"VNC") + with patch( + "virsh_panel.console.asyncio.create_subprocess_exec", + AsyncMock(return_value=process), + ): + await relay_console( + DisconnectingWebSocket(), port=5900, ssh_target="host.example" + ) + self.assertTrue(process.terminated) + + async def test_invalid_endpoint_never_spawns_ssh(self) -> None: + spawn = AsyncMock() + with patch("virsh_panel.console.asyncio.create_subprocess_exec", spawn): + for port, target in ( + (0, "host.example"), + (65536, "host.example"), + (True, "host.example"), + (5900, "-oProxyCommand=evil"), + (5900, "host.example ; evil"), + (5900, "ssh://host.example"), + ): + with self.subTest(port=port, target=target): + with self.assertRaises(ValueError): + await relay_console(FakeWebSocket(), port=port, ssh_target=target) + with self.assertRaises(ValueError): + await relay_console( + FakeWebSocket(), + port=5900, + ssh_target="host.example", + known_hosts_file="relative/known_hosts", + ) + with self.assertRaises(ValueError): + await relay_console( + FakeWebSocket(), + port=5900, + ssh_target="host.example", + ssh_config_file="relative/config", + ) + spawn.assert_not_awaited() + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/tests/test_database.py b/engine/tests/test_database.py new file mode 100644 index 00000000..e0590eb6 --- /dev/null +++ b/engine/tests/test_database.py @@ -0,0 +1,517 @@ +"""Database-backed state behavior without requiring a live MariaDB server.""" + +from __future__ import annotations + +import base64 +import json +import os +import stat +import struct +import subprocess +from pathlib import Path +from types import SimpleNamespace + +import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from virsh_panel.auth import hash_password, verify_password +from virsh_panel.cloud_templates import TemplateError +from virsh_panel.database import ( + DatabasePanelState, + DatabaseRemoteHostManager, + DatabaseStore, + DatabaseTemplateStore, +) +from virsh_panel.remote_host import HostProfile, RemoteHostError +from virsh_panel.ssh_agent import SSHAgentError + + +PRIVATE_KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\nZmFrZQ==\n-----END OPENSSH PRIVATE KEY-----\n" + + +class MemoryStore: + def __init__(self) -> None: + self.records: dict[tuple[str, str], str] = {} + + def get(self, kind: str, key: str) -> str | None: + return self.records.get((kind, key)) + + def set(self, kind: str, key: str, value: str) -> None: + self.records[(kind, key)] = value + + def insert(self, kind: str, key: str, value: str) -> bool: + if (kind, key) in self.records: + return False + self.records[(kind, key)] = value + return True + + def delete(self, kind: str, key: str) -> None: + self.records.pop((kind, key), None) + + def list(self, kind: str) -> dict[str, str]: + return {key: value for (record_type, key), value in self.records.items() + if record_type == kind} + + +class MemoryUsers: + def __init__(self, store: MemoryStore) -> None: + self.store = store + + def has_users(self) -> bool: + return self.store.get("test_user", "initial") is not None + + def create_initial_user(self, username: str, password: str, email=None): + self.store.set("test_user", "initial", json.dumps({ + "id": 1, "username": username, "email": email, + "password_hash": hash_password(password), "admin": False, + "approved": True, "email_verified": True, "created_at": 100, + })) + + def get_by_username(self, username: str): + record = self.store.get("test_user", "initial") + user = json.loads(record) if record else None + return user if user and user["username"] == username else None + + +class EncryptedMemoryStore(MemoryStore): + """Exercise the production record envelope without a MariaDB server.""" + + def __init__(self) -> None: + super().__init__() + self.records: dict[tuple[str, str], bytes] = {} + self._cipher_store = DatabaseStore.__new__(DatabaseStore) + self._cipher_store._cipher = AESGCM(b"a" * 32) + + def get(self, kind: str, key: str) -> str | None: + payload = self.records.get((kind, key)) + return (None if payload is None else + self._cipher_store._decrypt(kind, key, payload)) + + def set(self, kind: str, key: str, value: str) -> None: + self.records[(kind, key)] = self._cipher_store._encrypt(kind, key, value) + + +def test_database_ciphertext_is_randomized_and_bound_to_record_key(): + store = DatabaseStore.__new__(DatabaseStore) + store._cipher = AESGCM(b"a" * 32) + first = store._encrypt("secret", "gitea_token", "private-token") + second = store._encrypt("secret", "gitea_token", "private-token") + assert first != second + assert b"private-token" not in first + assert store._decrypt("secret", "gitea_token", first) == "private-token" + with pytest.raises(Exception, match="密文"): + store._decrypt("secret", "different_name", first) + with pytest.raises(Exception, match="密文"): + store._decrypt("secret", "gitea_token", first[:-1] + b"0") + + +def test_linux_tmpfs_agent_socket_path_fits_openssh_limit(): + # Linux pid_max cannot exceed 4,194,304; the runtime name is deliberately + # short so SSHAgentSession's <100-byte socket guard accepts it. + longest = ( + "/dev/shm/v4194304-abcd/generations/gen-" + "f" * 32 + + "/agent-" + "f" * 16 + ".sock" + ) + assert len(longest.encode()) < 100 + + +def test_non_linux_rejects_disk_backed_private_key_fallback(tmp_path, monkeypatch): + monkeypatch.setattr("virsh_panel.database.sys", SimpleNamespace(platform="darwin")) + data_dir = tmp_path / "panel" + with pytest.raises(RemoteHostError, match="仅支持 Linux"): + DatabaseRemoteHostManager(MemoryStore(), data_dir) + assert not list(data_dir.rglob("id_private")) + + +def test_initial_user_hash_is_database_only_and_bootstrap_token_is_consumed(tmp_path: Path): + store = MemoryStore() + data_dir = tmp_path / "panel" + state = DatabasePanelState(data_dir, store, MemoryUsers(store)) + token = state.initialize_setup_token() + assert token + state.create_admin(token, "admin", "a-valid-very-long-password") + assert not (data_dir / "state.json").exists() + assert not (data_dir / "setup-token").exists() + assert stat.S_IMODE(data_dir.stat().st_mode) == 0o700 + reopened = DatabasePanelState(data_dir, store, MemoryUsers(store)) + user = reopened.users.get_by_username("admin") + assert user["admin"] is False and user["approved"] is True + assert user["email"] is None + assert verify_password("a-valid-very-long-password", user["password_hash"]) + assert reopened.initialize_setup_token() is None + + +def test_templates_are_isolated_by_host_scope_and_atomic_insert(): + store = MemoryStore() + templates = DatabaseTemplateStore(store) + record = {"id": "alma10-12345678-abcdef0123456789", "name": "AlmaLinux"} + assert templates.add("a" * 64, record) == record + assert templates.list("a" * 64) == [record] + assert templates.list("b" * 64) == [] + with pytest.raises(TemplateError) as duplicate: + templates.add("a" * 64, record) + assert duplicate.value.status == 409 + + +def test_database_template_rename_persists_only_name_and_rejects_duplicate(): + store = MemoryStore() + templates = DatabaseTemplateStore(store) + scope = "a" * 64 + other_scope = "b" * 64 + record = { + "id": "alma9-12345678-abcdef0123456789", "name": "AlmaLinux 9", + "os_family": "AlmaLinux", "os_version": "9", "sha256": "f" * 64, + "volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2", + } + templates.add(scope, record) + templates.add(scope, {**record, "id": "second", "name": "Second"}) + templates.add(other_scope, {**record, "name": "Other host"}) + + with pytest.raises(TemplateError) as duplicate_import: + templates.add(scope, {**record, "id": "third", "name": "ALMALINUX 9"}) + assert duplicate_import.value.status == 409 + with pytest.raises(TemplateError) as wrong_host: + templates.rename(other_scope, "second", "Missing") + assert wrong_host.value.status == 404 + with pytest.raises(TemplateError) as duplicate_rename: + templates.rename(scope, record["id"], "second") + assert duplicate_rename.value.status == 409 + + updated = templates.rename(scope, record["id"], " 自定义名称 ") + assert updated == {**record, "name": "自定义名称"} + assert DatabaseTemplateStore(store).get(scope, record["id"]) == updated + assert templates.get(other_scope, record["id"])["name"] == "Other host" + + +def _host_key() -> str: + blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + b"a" * 32 + return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii") + + +def _fake_ssh(argv, **_kwargs): + if argv[0] == "ssh-keyscan": + return subprocess.CompletedProcess(argv, 0, "host.example " + _host_key() + "\n", "") + if argv[0] == "ssh-keygen": + return subprocess.CompletedProcess(argv, 0, "ssh-ed25519 fake-public-key\n", "") + if argv[0] == "ssh": + return subprocess.CompletedProcess(argv, 0, "ok", "") + raise AssertionError(argv) + + +def _encrypted_ssh(argv, **kwargs): + if argv[0] == "ssh-keygen": + return subprocess.CompletedProcess(argv, 255, "", "passphrase required") + return _fake_ssh(argv, **kwargs) + + +class FakeAgent: + def __init__(self, generation: Path, _key_path: Path, passphrase: str) -> None: + if passphrase != "open-sesame": + raise SSHAgentError("bad passphrase") + self.socket_path = generation / "fake-agent.sock" + self.public_key = _host_key() + self.alive = True + + def close(self) -> None: + self.alive = False + + +def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_path: Path): + store = MemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + data_dir = tmp_path / "panel" + first = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh, + ) + scan = first.scan("host.example", 22) + profile = HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], storage_pool="/home/kvm", + iso_pool="/home/iso", default_network="bridge:br0", region="东京", + public_pool_cidr="1.2.3.1/28", public_gateway="1.2.3.1", + public_dns_servers=["1.1.1.1", "8.8.8.8"], + public_reserved_ips=["1.2.3.10"], public_vm_prefix=24, + ) + staged = first.stage(profile, scan["fingerprint"]) + assert first.test(staged)["libvirt"] == "available" + current = first.commit(staged) + assert current["host"] == "host.example" + assert current["libvirt_uri"].find("runtime-wrappers") >= 0 + assert ("host", "current") in store.records + assert not list(data_dir.rglob("id_private")) + assert not list(data_dir.rglob("profile.json")) + first.close() + + second = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh, + ) + assert second.current()["storage_pool"] == "/home/kvm" + assert second.current()["default_network"] == "bridge:br0" + assert second.current()["region"] == "东京" + assert second.current()["public_pool_cidr"] == "1.2.3.0/28" + assert second.current()["public_vm_prefix"] == 24 + assert second.current()["public_gateway"] == "1.2.3.1" + assert second.current()["public_dns_servers"] == ["1.1.1.1", "8.8.8.8"] + assert second.current()["public_reserved_ips"] == ["1.2.3.10"] + assert (second._current_generation() / "id_private").read_text() == PRIVATE_KEY + assert not list(data_dir.rglob("id_private")) + second.close() + assert not list(runtime_parent.rglob("id_private")) + + legacy = json.loads(store.records[("host", "current")]) + legacy["metadata"].pop("region") + for key in ("public_pool_cidr", "public_gateway", "public_dns_servers", "public_reserved_ips", "public_vm_prefix"): + legacy["metadata"].pop(key) + store.records[("host", "current")] = json.dumps(legacy) + third = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh, + ) + assert third.current()["region"] == "" + assert third.current()["public_pool_cidr"] == "" + assert third.current()["public_gateway"] == "" + assert third.current()["public_dns_servers"] == [] + assert third.current()["public_vm_prefix"] is None + third.close() + + +def test_host_commit_does_not_read_database_after_activation(tmp_path: Path): + store = MemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + manager = DatabaseRemoteHostManager( + store, tmp_path / "panel", runtime_parent=runtime_parent, runner=_fake_ssh, + ) + scan = manager.scan("host.example", 22) + staged = manager.stage(HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], + ), scan["fingerprint"]) + manager.test(staged) + original_get = store.get + reads = 0 + + def one_read_only(kind: str, key: str) -> str | None: + nonlocal reads + reads += 1 + if reads > 1: + raise RuntimeError("database read unavailable after activation") + return original_get(kind, key) + + store.get = one_read_only + assert manager.commit(staged)["host"] == "host.example" + assert reads == 1 + assert ("host", "current") in store.records + manager.close() + + +def test_encrypted_host_key_auto_unlocks_after_process_restart(tmp_path: Path): + store = EncryptedMemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + data_dir = tmp_path / "panel" + first = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + scan = first.scan("host.example", 22) + staged = first.stage(HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", + ), scan["fingerprint"]) + first.test(staged) + saved = first.commit(staged) + assert saved["key_locked"] is False + assert saved["private_key_passphrase_saved"] is True + ciphertext = store.records[("host", "current")] + assert ciphertext.startswith(b"vp1") + assert b"open-sesame" not in ciphertext + assert b"open-sesame" not in b"".join( + path.read_bytes() for path in data_dir.rglob("*") if path.is_file() + ) + first.close() + second = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + assert second.current()["key_locked"] is False + assert second.current()["private_key_passphrase_saved"] is True + second.close() + + +def test_bad_saved_passphrase_keeps_host_locked_without_blocking_startup(tmp_path: Path): + store = MemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + data_dir = tmp_path / "panel" + first = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + scan = first.scan("host.example", 22) + staged = first.stage(HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", + ), scan["fingerprint"]) + first.test(staged) + first.commit(staged) + first.close() + + record = json.loads(store.get("host", "current")) + record["private_key_passphrase"] = "wrong-secret" + store.set("host", "current", json.dumps(record)) + attempts = [] + + def counting_agent(*args): + attempts.append(1) + return FakeAgent(*args) + + second = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=counting_agent, + ) + assert len(attempts) == 1 + assert second.current()["key_locked"] is True + assert second.current()["private_key_passphrase_saved"] is True + assert second.current_for_background()["key_locked"] is True + assert second.current_for_background()["key_locked"] is True + assert len(attempts) == 2 + assert second.unlock_current("open-sesame")["key_locked"] is False + second.close() + + +def test_background_recovers_ssh_agent_after_it_exits(tmp_path: Path): + store = MemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + manager = DatabaseRemoteHostManager( + store, tmp_path / "panel", runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + scan = manager.scan("host.example", 22) + staged = manager.stage(HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", + ), scan["fingerprint"]) + manager.test(staged) + manager.commit(staged) + generation = manager._current_generation() + manager._agents[generation].close() + assert manager.current()["key_locked"] is True + assert manager.current_for_background()["key_locked"] is False + manager.close() + + +def test_resaving_same_key_can_reuse_saved_passphrase(tmp_path: Path): + store = MemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + manager = DatabaseRemoteHostManager( + store, tmp_path / "panel", runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + scan = manager.scan("host.example", 22) + initial = manager.stage(HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", + ), scan["fingerprint"]) + manager.test(initial) + manager.commit(initial) + for key in ("", PRIVATE_KEY): + staged = manager.stage(HostProfile( + host="host.example", port=22, private_key=key, + host_key=scan["known_hosts_line"], private_key_passphrase="", + ), scan["fingerprint"]) + manager.test(staged) + assert manager.commit(staged)["private_key_passphrase_saved"] is True + assert json.loads(store.get("host", "current"))["private_key_passphrase"] == "open-sesame" + manager.close() + + +def test_replacing_key_cannot_inherit_previous_passphrase(tmp_path: Path): + store = MemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + manager = DatabaseRemoteHostManager( + store, tmp_path / "panel", runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + scan = manager.scan("host.example", 22) + initial = manager.stage(HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", + ), scan["fingerprint"]) + manager.test(initial) + manager.commit(initial) + previous = store.get("host", "current") + different_key = PRIVATE_KEY.replace("ZmFrZQ==", "b3RoZXI=") + with pytest.raises(RemoteHostError, match="填写私钥口令"): + manager.stage(HostProfile( + host="host.example", port=22, private_key=different_key, + host_key=scan["known_hosts_line"], private_key_passphrase="", + ), scan["fingerprint"]) + assert store.get("host", "current") == previous + manager.close() + + +def test_legacy_saved_host_requiring_password_remains_locked_until_resaved(tmp_path: Path): + store = MemoryStore() + runtime_parent = tmp_path / "simulated-tmpfs" + runtime_parent.mkdir() + data_dir = tmp_path / "panel" + first = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + scan = first.scan("host.example", 22) + initial = first.stage(HostProfile( + host="host.example", port=22, private_key=PRIVATE_KEY, + host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", + ), scan["fingerprint"]) + first.test(initial) + first.commit(initial) + record = json.loads(store.get("host", "current")) + record.pop("private_key_passphrase") + store.set("host", "current", json.dumps(record)) + first.close() + + second = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + assert second.current()["key_locked"] is True + assert second.current()["private_key_passphrase_saved"] is False + assert second.unlock_current("open-sesame")["key_locked"] is False + assert second.current()["private_key_passphrase_saved"] is False + staged = second.stage(HostProfile( + host="host.example", port=22, private_key="", + host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", + ), scan["fingerprint"]) + second.test(staged) + assert second.commit(staged)["private_key_passphrase_saved"] is True + second.close() + + third = DatabaseRemoteHostManager( + store, data_dir, runtime_parent=runtime_parent, + runner=_encrypted_ssh, agent_factory=FakeAgent, + ) + assert third.current()["key_locked"] is False + third.close() + + +def test_startup_prunes_only_marked_runtime_of_dead_process(tmp_path: Path, monkeypatch): + dead = tmp_path / "v99999999-dead" + live = tmp_path / f"v{os.getpid()}-abcd" + dead.mkdir(mode=0o700) + live.mkdir(mode=0o700) + (dead / ".owner").write_text("99999999:123\n") + (live / ".owner").write_text(f"{os.getpid()}:456\n") + (dead / ".owner").chmod(0o600) + (live / ".owner").chmod(0o600) + monkeypatch.setattr( + DatabaseRemoteHostManager, "_process_start_ticks", + staticmethod(lambda pid: "456" if pid == os.getpid() else None), + ) + DatabaseRemoteHostManager._clean_stale_runtime(tmp_path) + assert not dead.exists() + assert live.exists() diff --git a/engine/tests/test_database_bootstrap.py b/engine/tests/test_database_bootstrap.py new file mode 100644 index 00000000..1528a848 --- /dev/null +++ b/engine/tests/test_database_bootstrap.py @@ -0,0 +1,84 @@ +"""The only local durable configuration is encrypted database bootstrap data.""" + +from __future__ import annotations + +import json +import stat + +import pytest + +from virsh_panel.database_bootstrap import ( + DatabaseBootstrap, DatabaseSetupError, validate_database_config, +) + + +CONFIG = { + "host": "db.example.test", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "not-a-public-database-password", +} + + +def test_bootstrap_requires_token_and_encrypts_connection_settings(tmp_path): + bootstrap = DatabaseBootstrap(tmp_path / "data") + token = bootstrap.ensure_token() + assert bootstrap.ensure_token() == token + calls = [] + + def connect(config, key): + calls.append((config, key)) + return "connected" + + with pytest.raises(DatabaseSetupError) as wrong: + bootstrap.configure(CONFIG, "wrong-token", connect) + assert wrong.value.status == 403 + assert calls == [] + assert bootstrap.configure(CONFIG, token, connect) == "connected" + assert len(calls[0][1]) == 32 + assert bootstrap.load_config() == CONFIG + assert CONFIG["password"].encode() not in bootstrap.config_file.read_bytes() + assert CONFIG["username"].encode() not in bootstrap.config_file.read_bytes() + assert stat.S_IMODE(bootstrap.data_dir.stat().st_mode) == 0o700 + assert stat.S_IMODE(bootstrap.key_file.stat().st_mode) == 0o600 + assert stat.S_IMODE(bootstrap.config_file.stat().st_mode) == 0o600 + with pytest.raises(DatabaseSetupError) as repeated: + bootstrap.configure(CONFIG, token, connect) + assert repeated.value.status == 409 + + +def test_bootstrap_does_not_commit_failed_connection(tmp_path): + bootstrap = DatabaseBootstrap(tmp_path / "data") + token = bootstrap.ensure_token() + + def fail(_config, _key): + raise ConnectionError("database unavailable") + + with pytest.raises(ConnectionError): + bootstrap.configure(CONFIG, token, fail) + assert not bootstrap.configured() + assert bootstrap.ensure_token() == token + + +def test_bootstrap_rejects_tampering_and_unsafe_files(tmp_path): + bootstrap = DatabaseBootstrap(tmp_path / "data") + token = bootstrap.ensure_token() + bootstrap.configure(CONFIG, token, lambda *_: None) + envelope = json.loads(bootstrap.config_file.read_text()) + envelope["ciphertext"] = "AAAA" + bootstrap.config_file.write_text(json.dumps(envelope)) + with pytest.raises(ValueError, match="损坏"): + bootstrap.load_config() + bootstrap.config_file.chmod(0o644) + with pytest.raises(ValueError, match="0600"): + bootstrap.load_config() + + +@pytest.mark.parametrize("bad", [ + {**CONFIG, "host": "https://evil.example"}, + {**CONFIG, "port": 0}, + {**CONFIG, "database": "other;DROP TABLE admin"}, + {**CONFIG, "username": "bad\nname"}, + {**CONFIG, "password": ""}, +]) +def test_database_config_validation_rejects_unsafe_values(bad): + with pytest.raises(DatabaseSetupError): + validate_database_config(bad) diff --git a/engine/tests/test_database_http.py b/engine/tests/test_database_http.py new file mode 100644 index 00000000..0559295e --- /dev/null +++ b/engine/tests/test_database_http.py @@ -0,0 +1,439 @@ +"""First-run database and update routes with isolated in-memory dependencies.""" + +from __future__ import annotations + +import json +import stat +import sys +import threading +import types +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from types import SimpleNamespace + +from fastapi.testclient import TestClient + +# The HTTP boundary is tested with fake VM services; native libvirt is not +# available on ordinary development machines. +try: + import libvirt # noqa: F401 +except ModuleNotFoundError: + stub = types.ModuleType("libvirt") + stub.libvirtError = type("libvirtError", (Exception,), {}) + sys.modules["libvirt"] = stub + +from virsh_panel import app as app_module +from virsh_panel.auth import hash_password +from virsh_panel.config import Settings +from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore +from virsh_panel.users import UserError, normalize_email + + +class MemoryUsers: + """Only the SQL user-store boundary is replaced in isolated HTTP tests.""" + + def __init__(self, store): + self.store = store + + def has_users(self): + return any(kind == "test_user" for kind, _key in self.store.records) + + def get_by_username(self, username): + raw = self.store.get("test_user", username) + return json.loads(raw) if raw else None + + def get_by_email(self, email): + try: + email = normalize_email(email) + except UserError: + return None + for (kind, _key), raw in self.store.records.items(): + if kind == "test_user": + account = json.loads(raw) + if account["email"] == email: + return account + return None + + def get_by_id(self, user_id): + for (kind, _key), raw in self.store.records.items(): + if kind == "test_user": + user = json.loads(raw) + if user["id"] == user_id: + return user + return None + + def create_initial_user(self, username, password, email=None): + email = normalize_email(email) if email is not None else None + account = { + "id": 1, "username": username, "email": email, + "password_hash": hash_password(password), "admin": False, + "approved": True, "email_verified": True, "created_at": 100, + } + self.store.set("test_user", username, json.dumps(account)) + return account + + def promote(self, username): + account = self.get_by_username(username) + account["admin"] = True + self.store.set("test_user", username, json.dumps(account)) + + def owns_vm(self, host_scope, vm_id, user_id): + return self.store.get("test_vm_owner", f"{host_scope}:{vm_id}") == str(user_id) + + def assign_vm(self, host_scope, vm_id, user_id): + self.store.set("test_vm_owner", f"{host_scope}:{vm_id}", str(user_id)) + + def delete_vm_owner(self, host_scope, vm_id): + self.store.delete("test_vm_owner", f"{host_scope}:{vm_id}") + + def list_owned_vm_ids(self, host_scope, user_id): + prefix = f"{host_scope}:" + return {key[len(prefix):] for key, owner in self.store.list("test_vm_owner").items() + if key.startswith(prefix) and owner == str(user_id)} + + def list_pending_users(self): + pending = [] + for (kind, _key), raw in self.store.records.items(): + if kind == "test_user": + account = json.loads(raw) + if not account["approved"]: + pending.append({key: value for key, value in account.items() + if key != "password_hash"}) + return pending + + def approve_user(self, user_id): + account = self.get_by_id(user_id) + if account is None: + return None + account["approved"] = True + self.store.set("test_user", account["username"], json.dumps(account)) + return account + + @staticmethod + def generate_code(): + return "123456" + + def issue_registration_code(self, email, code): + if any(json.loads(raw)["email"] == email for (kind, _key), raw in self.store.records.items() + if kind == "test_user"): + return False + self.store.set("test_code", email, code) + return True + + def revoke_registration_code(self, email, code): + if self.store.get("test_code", email) != code: + return False + self.store.delete("test_code", email) + return True + + def register_with_code(self, username, email, password, code): + if self.store.get("test_code", email) != code: + raise UserError("验证码无效或已过期") + email = normalize_email(email) + if self.get_by_username(username) is not None or self.get_by_email(email) is not None: + raise UserError("用户名或邮箱已存在", 409) + account = { + "id": 1 + sum(kind == "test_user" for kind, _key in self.store.records), + "username": username, "email": email, + "password_hash": hash_password(password), "admin": False, + "approved": False, "email_verified": True, "created_at": 101, + } + self.store.set("test_user", username, json.dumps(account)) + self.store.delete("test_code", email) + return account + + +class MemoryStore: + def __init__(self) -> None: + self.records = {} + self.users = MemoryUsers(self) + + def get(self, kind, key): + return self.records.get((kind, key)) + + def set(self, kind, key, value): + self.records[(kind, key)] = value + + def insert(self, kind, key, value): + if (kind, key) in self.records: + return False + self.set(kind, key, value) + return True + + def delete(self, kind, key): + self.records.pop((kind, key), None) + + def list(self, kind): + return {key: value for (record_type, key), value in self.records.items() + if record_type == kind} + + def get_secret(self, key): + return self.get("secret", key) + + def set_secret(self, key, value): + self.set("secret", key, value) + + def get_value(self, key): + return self.get("value", key) + + def set_value(self, key, value): + self.set("value", key, value) + + +class FakeManager: + def current(self): + return None + + def close(self): + pass + + +def test_first_run_requires_database_then_admin_and_ignores_old_json(monkeypatch, tmp_path): + data_dir = tmp_path / "data" + data_dir.mkdir(mode=0o700) + (data_dir / "state.json").write_text( + '{"version":1,"admin":{"username":"old","password_hash":"old"}}', + encoding="utf-8", + ) + store = MemoryStore() + calls = [] + + def make_components(directory, config, key, _ssh_binary): + calls.append((config, key)) + return (DatabasePanelState(directory, store, store.users), FakeManager(), + DatabaseTemplateStore(store), store) + + monkeypatch.setattr(app_module, "make_components", make_components) + settings = Settings(data_dir=data_dir, + static_dir=Path(__file__).resolve().parents[1] / "static") + app = app_module.create_app(settings) + token = (data_dir / "setup-token").read_text(encoding="ascii").strip() + config = { + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "test-database-password", + } + with TestClient(app, base_url="https://panel.example.test") as client: + assert client.get("/api/v1/database/status").json() == { + "configured": False, "setup_required": True, + } + assert client.get("/api/v1/setup/status").status_code == 409 + assert client.post("/api/v1/database/setup", json={ + **config, "setup_token": "invalid", + }).status_code == 403 + assert calls == [] + response = client.post("/api/v1/database/setup", json={ + **config, "setup_token": token, + }) + assert response.status_code == 200 + assert response.json() == {"configured": True} + assert calls[0][0] == config and len(calls[0][1]) == 32 + assert client.get("/api/v1/setup/status").json() == {"setup_required": True} + created = client.post("/api/v1/setup/admin", json={ + "token": token, "username": "admin", + "password": "correct-horse-battery-staple", + }) + assert created.status_code == 200 + assert client.get("/api/v1/setup/status").json() == {"setup_required": False} + session_cookie = client.cookies.get("virsh_panel_session") + assert ("test_user", "admin") in store.records + assert store.users.get_by_username("admin")["admin"] is False + assert store.users.get_by_username("admin")["email"] is None + assert store.users.get_by_email("admin@example.test") is None + assert not (data_dir / "setup-token").exists() + encrypted = (data_dir / "database-config.json").read_bytes() + assert b"test-database-password" not in encrypted + assert stat.S_IMODE((data_dir / "master.key").stat().st_mode) == 0o600 + store.set("import_job", "interrupted-job", json.dumps({ + "status": "running", "scope": "previous-host", + })) + restarted = app_module.create_app(settings) + assert json.loads(store.get("import_job", "interrupted-job"))["status"] == "failed" + with TestClient(restarted, base_url="https://panel.example.test") as client: + client.cookies.set("virsh_panel_session", session_cookie) + assert client.get("/api/v1/session").json()["authenticated"] is True + + +def test_update_routes_require_auth_and_never_return_token(monkeypatch, tmp_path): + data_dir = tmp_path / "data" + store = MemoryStore() + monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( + DatabasePanelState(directory, store, store.users), FakeManager(), + DatabaseTemplateStore(store), store, + )) + settings = Settings(data_dir=data_dir, + static_dir=Path(__file__).resolve().parents[1] / "static") + app = app_module.create_app(settings) + token = (data_dir / "setup-token").read_text(encoding="ascii").strip() + + class FakeUpdater: + def __init__(self, *_args): + self.token = None + self.job = None + + def settings(self): + return { + "repository": "https://g.luoli.live/root/virt.git", "branch": "main", + "token_configured": self.token is not None, "checkout_ready": True, + "current_commit": "a" * 40, "active_job_id": None, + } + + def set_token(self, token): + self.token = token + + def check(self): + return { + "repository": "https://g.luoli.live/root/virt.git", "branch": "main", + "current_commit": "a" * 40, "remote_commit": "b" * 40, + "status": "update_available", + } + + def create_job(self, *, expected_current_commit=None, expected_remote_commit=None): + assert expected_current_commit == "a" * 40 + assert expected_remote_commit == "b" * 40 + self.job = {"job_id": "test-job-00000001", "status": "queued"} + return self.job + + def get_job(self, job_id): + return self.job if self.job and job_id == self.job["job_id"] else None + + def fail_job(self, job_id, error): + self.job = {"job_id": job_id, "status": "failed", "error": error} + + monkeypatch.setattr(app_module, "Updater", FakeUpdater) + monkeypatch.setattr(app_module.subprocess, "run", lambda *args, **kwargs: + SimpleNamespace(returncode=0, stdout="inactive")) + with TestClient(app, base_url="https://panel.example.test") as client: + assert client.get("/api/v1/update/settings").status_code == 401 + client.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "test-database-password", + "setup_token": token, + }) + response = client.post("/api/v1/setup/admin", json={ + "token": token, "username": "admin", + "password": "correct-horse-battery-staple", + }) + assert response.status_code == 200 + store.users.promote("admin") + csrf = response.json()["csrf_token"] + assert client.put("/api/v1/update/settings", json={ + "access_token": "some-very-private-gitea-token", + }).status_code == 403 + saved = client.put("/api/v1/update/settings", json={ + "access_token": "some-very-private-gitea-token", + }, headers={"X-CSRF-Token": csrf}) + assert saved.status_code == 200 + assert saved.json()["configured"] is True + assert "some-very-private-gitea-token" not in saved.text + checked = client.post("/api/v1/update/check", headers={ + "X-CSRF-Token": csrf, + }) + assert checked.status_code == 200 + assert checked.json()["update_available"] is True + queued = client.post("/api/v1/update/apply", json={ + "expected_current_commit": "a" * 40, + "expected_remote_commit": "b" * 40, + }, headers={ + "X-CSRF-Token": csrf, + }) + assert queued.status_code == 202 + job_id = queued.json()["job_id"] + assert client.get(f"/api/v1/update/jobs/{job_id}").json()["status"] == "queued" + + +def test_vm_creation_finishes_before_update_is_queued(monkeypatch, tmp_path): + data_dir = tmp_path / "data" + store = MemoryStore() + vm_started = threading.Event() + release_vm = threading.Event() + update_received = threading.Event() + update_queued = threading.Event() + + class ConfiguredManager(FakeManager): + def current(self): + return {"key_locked": False} + + class BlockingVMService: + def create_vm(self, spec): + vm_started.set() + assert release_vm.wait(timeout=5), "test did not release VM creation" + return {"uuid": spec["vm_uuid"]} + + class FakeUpdater: + def __init__(self, _repo_dir, data_store): + self.store = data_store + self.job = None + + def create_job(self, **_kwargs): + self.job = {"job_id": "test-job-00000001", "status": "queued"} + self.store.set_value("update.active_job", self.job["job_id"]) + update_queued.set() + return self.job + + def get_job(self, job_id): + return self.job if self.job and job_id == self.job["job_id"] else None + + def fail_job(self, _job_id, _message): + raise AssertionError("the mocked update service must start") + + monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( + DatabasePanelState(directory, store, store.users), ConfiguredManager(), + DatabaseTemplateStore(store), store, + )) + monkeypatch.setattr(app_module, "Updater", FakeUpdater) + monkeypatch.setattr( + app_module.subprocess, "run", + lambda argv, **_kwargs: SimpleNamespace( + returncode=3 if "is-active" in argv else 0, + stdout="inactive" if "is-active" in argv else "", + ), + ) + settings = Settings(data_dir=data_dir, + static_dir=Path(__file__).resolve().parents[1] / "static") + app = app_module.create_app(settings, service_factory=lambda _profile: BlockingVMService()) + + @app.middleware("http") + async def observe_update(request, call_next): + if request.url.path == "/api/v1/update/apply": + update_received.set() + return await call_next(request) + + token = (data_dir / "setup-token").read_text(encoding="ascii").strip() + with TestClient(app, base_url="https://panel.example.test") as client: + configured = client.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "test-database-password", + "setup_token": token, + }) + assert configured.status_code == 200 + admin = client.post("/api/v1/setup/admin", json={ + "token": token, "username": "admin", + "password": "correct-horse-battery-staple", + }) + assert admin.status_code == 200 + store.users.promote("admin") + headers = {"X-CSRF-Token": admin.json()["csrf_token"]} + with ThreadPoolExecutor(max_workers=2) as executor: + creating = executor.submit(client.post, "/api/v1/vms", json={ + "name": "new-vm", "vcpu": 2, "memory_mib": 2048, + "disk_gib": 20, "network": "default", "iso": "AlmaLinux-10.iso", + }, headers=headers) + assert vm_started.wait(timeout=5) + updating = executor.submit(client.post, "/api/v1/update/apply", json={ + "expected_current_commit": "a" * 40, + "expected_remote_commit": "b" * 40, + }, headers=headers) + try: + assert update_received.wait(timeout=5) + assert not update_queued.wait(timeout=0.2) + assert not updating.done() + finally: + release_vm.set() + assert creating.result(timeout=5).status_code == 201 + assert updating.result(timeout=5).status_code == 202 + assert update_queued.is_set() + blocked = client.post("/api/v1/vms", json={ + "name": "another-vm", "vcpu": 2, "memory_mib": 2048, + "disk_gib": 20, "network": "default", "iso": "AlmaLinux-10.iso", + }, headers=headers) + assert blocked.status_code == 409 diff --git a/engine/tests/test_engine_boundary.py b/engine/tests/test_engine_boundary.py new file mode 100644 index 00000000..785079a6 --- /dev/null +++ b/engine/tests/test_engine_boundary.py @@ -0,0 +1,413 @@ +"""Private engine tests: no PHP cookies, no real DB and no real hypervisor.""" +from __future__ import annotations + +import base64 +import asyncio +import hashlib +import json +import threading +from contextlib import contextmanager +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest +from fastapi.testclient import TestClient + +from test_app import CREATE_BODY, FakeRemoteManager, FakeVMService, HOST_BODY, VM_ID +from virsh_panel.app import create_app +from virsh_panel.config import Settings +from virsh_panel.database import DatabaseTemplateStore +from virsh_panel.engine_context import (EngineComponents, ExternalOwnership, HostStore, + LogStore, MainStore, TRUSTED_ACTOR) +from virsh_panel.engine_security import (EngineAuthError, authenticate, encode_actor, + signed_headers) +from virsh_panel.internal import EngineApplication, HostRegistry +from virsh_panel.metrics import host_scope + + +SECRET = b"s" * 32 +USER = {"user_id": 41, "is_admin": False, "is_super_admin": False, + "can_manage": True, "session_id": "test-session"} +SUPER = {**USER, "user_id": 1, "is_admin": True, "is_super_admin": True} +ADMIN = {**SUPER, "is_super_admin": False} + + +class MemoryStore: + def __init__(self): + self.records = {} + self.nonces = set() + self.lock = threading.RLock() + + def get(self, kind, key): + with self.lock: + return self.records.get((kind, key)) + + def set(self, kind, key, value): + with self.lock: + self.records[kind, key] = value + + def insert(self, kind, key, value): + with self.lock: + if (kind, key) in self.records: + return False + self.records[kind, key] = value + return True + + def delete(self, kind, key): + with self.lock: + self.records.pop((kind, key), None) + + def list(self, kind): + with self.lock: + return {key: value for (row_kind, key), value in self.records.items() if row_kind == kind} + + def consume_nonce(self, nonce, expires_at, now): + with self.lock: + if nonce in self.nonces: + return False + self.nonces.add(nonce) + return True + + def query_metric_samples(self, *args, **kwargs): + return [{"timestamp": 123, "cpu_percent": 20.0}] + + +class Service(FakeVMService): + def __init__(self): + super().__init__() + self.create_failure = False + self.absent = False + self.vm.update(managed=True, os_source="iso") + + def create_vm(self, spec): + self.calls.append(("create_vm", spec)) + if self.create_failure: + from virsh_panel.libvirt_service import VMError + raise VMError("宿主机失联,回滚状态不明", 502) + self.vm.update(uuid=spec["vm_uuid"], name=spec["name"]) + return self.vm.copy() + + def provisioning_absent(self, vm_uuid, name): + return self.absent + + +@pytest.fixture +def boundary(tmp_path): + store = MemoryStore() + logs = MemoryStore() + config = {"service_secret": base64.b64encode(SECRET).decode(), "data_dir": str(tmp_path)} + services = {} + def factory(host_id): + (tmp_path / host_id).mkdir(mode=0o700, exist_ok=True) + scoped = HostStore(store, host_id) + manager = FakeRemoteManager() + manager.profile = {"host_id": host_id, "host": "host.example.test", "port": 22, + "fingerprint": "SHA256:example", "key_locked": False, "storage_pool": "images", + "iso_pool": "iso", "rescue_iso_pool": "rescue", "default_network": "default", + "libvirt_uri": "fake", "ssh_target": "fake", "ssh_config_file": "/fake/config", + "ssh_known_hosts_file": "/fake/known_hosts"} + service = Service() + services[host_id] = service + components = EngineComponents(SimpleNamespace(users=ExternalOwnership(scoped)), manager, + DatabaseTemplateStore(scoped), scoped, logs) + app = create_app(Settings(data_dir=tmp_path / host_id), engine_components=components, + service_factory=lambda profile: service) + return components, app + registry = HostRegistry(config, store, logs, factory=factory) + async def active(*args): + return True + engine = EngineApplication(config, store, logs, registry=registry, introspection=active) + engine._service = lambda profile: services[profile["host_id"]] + with TestClient(engine, base_url="http://127.0.0.1") as client: + yield client, engine, store, logs, services + + +def call(client, method, path, actor=USER, value=None, raw=None, headers=None): + body = raw if raw is not None else b"" if value is None else json.dumps(value, separators=(",", ":")).encode() + signed = signed_headers(SECRET, method, path, body, actor) + if value is not None: + signed["Content-Type"] = "application/json" + signed.update(headers or {}) + return client.request(method, path, content=body, headers=signed) + + +def test_hmac_binds_actor_payload_target_and_rejects_replay(): + store = MemoryStore() + body = b"{}" + target = "/internal/v1/hosts/hk/vms?range=1h" + headers = {key.lower(): value for key, value in signed_headers(SECRET, "POST", target, body, USER, + timestamp=1000, nonce="n" * 24).items()} + assert authenticate(headers, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1000) == USER + with pytest.raises(EngineAuthError): + authenticate(headers, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1000) + changed = {**headers, "x-cloud-actor": encode_actor(SUPER)} + with pytest.raises(EngineAuthError): + authenticate(changed, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1000) + with pytest.raises(EngineAuthError): + authenticate(headers, SECRET, "POST", target + "x", hashlib.sha256(body).hexdigest(), store, now=1000) + with pytest.raises(EngineAuthError): + authenticate(headers, SECRET, "POST", target, hashlib.sha256(b"other").hexdigest(), store, now=1000) + with pytest.raises(EngineAuthError): + authenticate(headers, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1061) + + +def test_private_route_allowlist_and_no_browser_admin_cookie(boundary): + client, *_ = boundary + for path in ("/api/v1/vms", "/internal/v1/hosts/hk/register", "/internal/v1/hosts/hk/setup/admin", + "/internal/v1/hosts/hk/update/apply", "/internal/v1/hosts/hk/smtp/settings"): + assert call(client, "POST", path, SUPER, {}).status_code == 404 + assert client.get("/internal/v1/hosts/hk/vms", cookies={"virsh_panel_session": "admin"}).status_code == 401 + assert TRUSTED_ACTOR.get() is None + + +def test_user_admin_super_admin_boundaries_and_cross_user_vm(boundary): + client, engine, *_ = boundary + path = "/internal/v1/hosts/hk" + assert call(client, "GET", path + "/host").status_code == 403 + assert call(client, "GET", path + "/host", ADMIN).status_code == 200 + assert call(client, "POST", path + "/host/scan", ADMIN, {"host": "x", "port": 22}).status_code == 403 + assert call(client, "POST", path + "/host/scan", SUPER, {"host": "x", "port": 22}).status_code == 200 + assert call(client, "POST", "/internal/v1/hosts/scan", ADMIN, {"host": "x", "port": 22}).status_code == 403 + component = engine.registry.components["hk"] + component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41) + assert call(client, "GET", path + f"/vms/{VM_ID}").status_code == 200 + assert call(client, "GET", path + f"/vms/{VM_ID}", {**USER, "user_id": 42}).status_code == 404 + assert call(client, "GET", path + "/vms", {**USER, "user_id": 42}).json()["items"] == [] + assert call(client, "POST", path + f"/vms/{VM_ID}/actions", {**USER, "can_manage": False}, + {"action": "reboot"}).status_code == 403 + + +def test_stable_host_identity_and_namespaces(): + store = MemoryStore() + first, second = HostStore(store, "a"), HostStore(store, "b") + first.set("host", "current", "one") + second.set("host", "current", "two") + assert first.get("host", "current") == "one" + assert second.get("host", "current") == "two" + a = {"host_id": "a", "host": "1.2.3.4", "port": 22, "fingerprint": "old"} + assert host_scope(a) == host_scope({**a, "host": "changed", "port": 2222, "fingerprint": "new"}) + assert host_scope(a) != host_scope({**a, "host_id": "b"}) + assert MainStore.RECORD_TABLE == "engine_records" + assert LogStore.METRIC_TABLE == "engine_vm_metric_samples" + + +def test_only_paid_operations_can_create_and_retry_never_duplicates(boundary): + client, engine, store, _, services = boundary + path = "/internal/v1/hosts/hk/vms" + assert call(client, "POST", path, USER, CREATE_BODY).status_code == 403 + provisioning = {**USER, "can_provision": True, "operation_id": "order-000001"} + created = call(client, "POST", path, provisioning, CREATE_BODY) + assert created.status_code == 201, created.text + vm_id = created.json()["uuid"] + assert created.json()["result"]["uuid"] == vm_id + assert created.json()["status"] == "succeeded" + component = engine.registry.components["hk"] + assert component.state.users.owns_vm(host_scope(component.manager.profile), vm_id, 41) + again = call(client, "POST", path, provisioning, CREATE_BODY) + assert again.status_code == 201 and again.json()["uuid"] == vm_id + assert len([row for row in services["hk"].calls if row[0] == "create_vm"]) == 1 + assert call(client, "POST", path, provisioning, {**CREATE_BODY, "vcpu": 4}).status_code == 409 + operation = call(client, "GET", "/internal/v1/operations/order-000001").json() + assert operation["status"] == "succeeded" and operation["result"]["uuid"] == vm_id + assert operation["safe_to_refund"] is False + assert call(client, "GET", "/internal/v1/operations/order-000001", {**USER, "user_id": 42}).status_code == 404 + + +def test_uncertain_creation_never_refunds_or_recreates(boundary): + client, engine, store, _, services = boundary + path = "/internal/v1/hosts/hk/vms" + call(client, "GET", path) + services["hk"].create_failure = True + actor = {**USER, "can_provision": True, "operation_id": "order-uncertain"} + failed = call(client, "POST", path, actor, CREATE_BODY) + assert failed.status_code == 502 + assert failed.json()["status"] == "uncertain" and not failed.json()["safe_to_refund"] + record = json.loads(store.get("operation", "order-uncertain")) + component = engine.registry.components["hk"] + scope = host_scope(component.manager.profile) + assert component.state.users.owns_vm(scope, record["vm_uuid"], 41) + component.store.set("vm_credential", f"{scope}.{record['vm_uuid']}", "saved-password") + component.store.set("ip_claim", f"{scope}.192.0.2.1", json.dumps({"vm_uuid": record["vm_uuid"]})) + again = call(client, "POST", path, actor, CREATE_BODY) + assert again.status_code == 202 and again.json()["status"] == "uncertain" + assert len([row for row in services["hk"].calls if row[0] == "create_vm"]) == 1 + services["hk"].absent = True + operation = call(client, "GET", "/internal/v1/operations/order-uncertain").json() + assert operation["status"] == "failed" and operation["safe_to_refund"] is True + assert not component.state.users.owns_vm(scope, record["vm_uuid"], 41) + assert component.store.get("vm_credential", f"{scope}.{record['vm_uuid']}") is None + assert component.store.list("ip_claim") == {} + + +@pytest.mark.parametrize("payload", [{"name": "invalid"}, ["not-an-object"], + {**CREATE_BODY, "guest_ssh_key_id": 3}]) +def test_rejected_create_has_durable_safe_failure_even_when_response_is_lost(boundary, payload): + client, engine, _, _, services = boundary + path = "/internal/v1/hosts/hk/vms" + actor = {**USER, "can_provision": True, "operation_id": "rejected-create"} + response = call(client, "POST", path, actor, payload) + assert response.status_code == 422 + # Simulate a dispatcher losing the POST response and querying after restart. + engine.active_operations.clear() + saved = call(client, "GET", "/internal/v1/operations/rejected-create").json() + assert saved["status"] == "failed" and saved["safe_to_refund"] is True + assert call(client, "POST", path, actor, payload).status_code == 422 + assert call(client, "POST", path, actor, CREATE_BODY).status_code == 409 + assert not any(row[0] == "create_vm" for row in services["hk"].calls) + + +def test_admin_created_vm_also_has_external_owner(boundary): + client, engine, *_ = boundary + actor = {**SUPER, "can_provision": True, "operation_id": "order-admin"} + response = call(client, "POST", "/internal/v1/hosts/hk/vms", actor, CREATE_BODY) + assert response.status_code == 201 + components = engine.registry.components["hk"] + assert components.state.users.owns_vm(host_scope(components.manager.profile), response.json()["uuid"], 1) + + +def test_power_action_has_persistent_idempotency(boundary): + client, engine, _, _, services = boundary + call(client, "GET", "/internal/v1/hosts/hk/vms") + components = engine.registry.components["hk"] + components.state.users.assign_vm(host_scope(components.manager.profile), VM_ID, 41) + path = f"/internal/v1/hosts/hk/vms/{VM_ID}/actions" + assert call(client, "POST", path, USER, {"action": "reboot"}).status_code == 403 + actor = {**USER, "operation_id": "reboot-operation"} + assert call(client, "POST", path, actor, {"action": "reboot"}).status_code == 200 + assert call(client, "POST", path, actor, {"action": "reboot"}).status_code == 200 + assert len([row for row in services["hk"].calls if row[0] == "action"]) == 1 + assert call(client, "POST", path, actor, {"action": "poweroff"}).status_code == 409 + operation = call(client, "GET", "/internal/v1/operations/reboot-operation").json() + assert operation["status"] == "succeeded" and operation["safe_to_refund"] is False + + +def test_async_mutation_operation_survives_lost_job_response_and_does_not_retry(boundary): + client, engine, store, *_ = boundary + call(client, "GET", "/internal/v1/hosts/hk/vms") + components = engine.registry.components["hk"] + job = {"operation_id": "lost-rescue-job", "owner": "php:41", "vm_id": VM_ID, + "status": "running", "phase": "正在救援"} + components.store.set("rescue_job", "job-abc", json.dumps(job)) + operation = {"operation_id": "lost-rescue-job", "host_id": "hk", "user_id": 41, + "kind": "mutation", "resource": f"vms/{VM_ID}/rescue", "vm_uuid": VM_ID, + "status": "uncertain", "result": None, "safe_to_refund": False} + store.set("operation", "lost-rescue-job", json.dumps(operation)) + recovered = call(client, "GET", "/internal/v1/operations/lost-rescue-job").json() + assert recovered["status"] == "running" and recovered["result"]["vm_id"] == VM_ID + job.update(status="completed", phase="救援系统启动") + components.store.set("rescue_job", "job-abc", json.dumps(job)) + completed = call(client, "GET", "/internal/v1/operations/lost-rescue-job").json() + assert completed["status"] == "succeeded" + assert not completed["safe_to_refund"] + + +def test_interrupted_async_job_stays_uncertain(boundary): + client, engine, store, *_ = boundary + call(client, "GET", "/internal/v1/hosts/hk/vms") + components = engine.registry.components["hk"] + components.store.set("reinstall_job", "job-abcd", json.dumps({ + "operation_id": "interrupted-job", "owner": "php:41", "vm_id": VM_ID, + "status": "failed", "phase": "面板重启,任务已中断"})) + store.set("operation", "interrupted-job", json.dumps({"operation_id": "interrupted-job", + "host_id": "hk", "user_id": 41, "kind": "mutation", "resource": f"vms/{VM_ID}/reinstall", + "vm_uuid": VM_ID, "status": "pending", "result": None, "safe_to_refund": False})) + recovered = call(client, "GET", "/internal/v1/operations/interrupted-job").json() + assert recovered["status"] == "uncertain" + + +def test_metrics_query_uses_log_store_and_owner_permission(boundary): + client, engine, *_ = boundary + call(client, "GET", "/internal/v1/hosts/hk/vms") + component = engine.registry.components["hk"] + component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41) + response = call(client, "GET", f"/internal/v1/hosts/hk/vms/{VM_ID}/metrics?range=30d") + assert response.status_code == 200 and response.json()["points"][0]["cpu_percent"] == 20 + + +def test_console_ticket_is_one_use_session_bound_and_no_url_secret(boundary): + client, engine, store, *_ = boundary + call(client, "GET", "/internal/v1/hosts/hk/vms") + component = engine.registry.components["hk"] + component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41) + issued = call(client, "POST", f"/internal/v1/hosts/hk/vms/{VM_ID}/console-ticket", USER, {}) + assert issued.status_code == 200, issued.text + assert issued.json()["websocket_path"] == "/engine-console" + ticket = issued.json()["ticket"] + key = hashlib.sha256(ticket.encode()).hexdigest() + record = json.loads(store.get("console_ticket", key)) + assert record["actor"]["user_id"] == 41 and record["actor"]["session_id"] == "test-session" + assert call(client, "POST", f"/internal/v1/hosts/hk/vms/{VM_ID}/console-ticket", + {**USER, "user_id": 42}, {}).status_code == 404 + from starlette.websockets import WebSocketDisconnect + with pytest.raises(WebSocketDisconnect): + with client.websocket_connect("wss://panel.example.test/engine-console", headers={"Origin": "https://evil.example"}, + subprotocols=["cloud-ticket." + ticket]): + pass + assert store.get("console_ticket", key) is not None + + +def test_console_consumes_ticket_and_closes_after_php_session_revocation(boundary): + client, engine, store, *_ = boundary + call(client, "GET", "/internal/v1/hosts/hk/vms") + component = engine.registry.components["hk"] + component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41) + checks = 0 + async def active(*args): + nonlocal checks + checks += 1 + return checks <= 2 # Ticket issuance + handshake; then PHP revokes. + engine.introspection = active + engine.console_check_interval = 0.01 + issued = call(client, "POST", f"/internal/v1/hosts/hk/vms/{VM_ID}/console-ticket", USER, {}) + ticket = issued.json()["ticket"] + protocol = "cloud-ticket." + ticket + async def relay(socket, **kwargs): + await socket.send_bytes(b"vnc") + await asyncio.Event().wait() + from starlette.websockets import WebSocketDisconnect + with patch("virsh_panel.console.relay_console", relay): + with client.websocket_connect("wss://panel.example.test/engine-console", + headers={"Origin": "https://panel.example.test"}, subprotocols=[protocol]) as socket: + assert socket.accepted_subprotocol == protocol + assert socket.receive_bytes() == b"vnc" + with pytest.raises(WebSocketDisconnect): + socket.receive_bytes() + key = hashlib.sha256(ticket.encode()).hexdigest() + assert store.get("console_ticket", key) is None + assert store.get("ticket_used", key) == "1" + with pytest.raises(WebSocketDisconnect): + with client.websocket_connect("wss://panel.example.test/engine-console", + headers={"Origin": "https://panel.example.test"}, subprotocols=[protocol]): + pass + + +def test_streamed_iso_digest_must_match_before_import_is_queued(boundary): + client, engine, store, _, services = boundary + path = "/internal/v1/hosts/hk/rescue-templates?name=rescue" + signed_body = b"A" * (1024 * 1024) + wrong_body = b"B" * len(signed_body) + signed = signed_headers(SECRET, "POST", path, signed_body, SUPER) + signed["X-Cloud-Content-SHA256"] = hashlib.sha256(signed_body).hexdigest() + signed["Content-Type"] = "application/octet-stream" + response = client.post(path, content=wrong_body, headers=signed) + assert response.status_code == 401, response.text + assert not any(row[0] == "import_rescue_iso" for row in services["hk"].calls) + assert engine.registry.components["hk"].store.list("rescue_import_job") == {} + + +def test_main_and_log_schema_do_not_create_python_accounts_or_cross_database_tables(): + connection = MagicMock() + cursor = connection.cursor.return_value.__enter__.return_value + config = {"host": "db", "port": 3306, "database": "main", "username": "engine", "password": "test", + "ssl_ca": "/private/test/ca.pem"} + with patch("virsh_panel.database.pymysql.connect", return_value=connection): + main = MainStore(config, b"m" * 32) + statements = [call.args[0] for call in cursor.execute.call_args_list] + assert any("engine_records" in statement for statement in statements) + assert not any("CREATE TABLE IF NOT EXISTS users" in statement for statement in statements) + assert not any("vm_metric_samples" in statement for statement in statements) + assert main._config["ssl_verify_identity"] is True + cursor.reset_mock() + LogStore({**config, "database": "logs"}, b"m" * 32) + statements = [call.args[0] for call in cursor.execute.call_args_list] + assert len(statements) == 1 and "engine_vm_metric_samples" in statements[0] diff --git a/engine/tests/test_frontend_page_layout.py b/engine/tests/test_frontend_page_layout.py new file mode 100644 index 00000000..60db9c75 --- /dev/null +++ b/engine/tests/test_frontend_page_layout.py @@ -0,0 +1,200 @@ +"""Keep VM creation and reinstall in the dashboard, not in modal dialogs.""" + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass +from html.parser import HTMLParser +from pathlib import Path + +import pytest + + +STATIC_DIR = Path(__file__).resolve().parents[1] / "static" +VOID_TAGS = { + "area", "base", "br", "col", "embed", "hr", "img", "input", + "link", "meta", "param", "source", "track", "wbr", +} + + +@dataclass(frozen=True) +class Element: + tag: str + attrs: dict[str, str | None] + ancestors: tuple[Element, ...] + + @property + def element_id(self) -> str | None: + return self.attrs.get("id") + + +class PageParser(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.stack: list[Element] = [] + self.elements: list[Element] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + element = Element(tag, dict(attrs), tuple(self.stack)) + self.elements.append(element) + if tag not in VOID_TAGS: + self.stack.append(element) + + def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + self.elements.append(Element(tag, dict(attrs), tuple(self.stack))) + + def handle_endtag(self, tag: str) -> None: + for index in range(len(self.stack) - 1, -1, -1): + if self.stack[index].tag == tag: + del self.stack[index:] + return + + +@pytest.fixture(scope="module") +def page() -> tuple[list[Element], dict[str, list[Element]]]: + parser = PageParser() + parser.feed((STATIC_DIR / "index.html").read_text(encoding="utf-8")) + assert not parser.stack, "Unclosed HTML element in the dashboard page" + by_id: dict[str, list[Element]] = defaultdict(list) + for element in parser.elements: + if element.element_id: + by_id[element.element_id].append(element) + return parser.elements, by_id + + +@pytest.mark.parametrize("prefix", ["create", "reinstall"]) +def test_vm_form_is_a_dashboard_page_not_a_modal(page, prefix: str) -> None: + _, by_id = page + forms = by_id[f"{prefix}-form"] + assert len(forms) == 1 + form = forms[0] + assert form.tag == "form" + ancestor_ids = {ancestor.element_id for ancestor in form.ancestors} + assert {"dashboard-view", "vm-workspace", f"{prefix}-view"} <= ancestor_ids + + for element in (*form.ancestors, form): + assert element.tag != "dialog" + assert element.attrs.get("role") != "dialog" + assert "modal-backdrop" not in (element.attrs.get("class") or "").split() + + back_buttons = by_id[f"{prefix}-back"] + assert len(back_buttons) == 1 + assert back_buttons[0].tag == "button" + assert f"{prefix}-view" in { + ancestor.element_id for ancestor in back_buttons[0].ancestors + } + + +def test_old_vm_modal_elements_and_js_references_are_removed(page) -> None: + _, by_id = page + script = (STATIC_DIR / "app.js").read_text(encoding="utf-8") + for element_id in ("create-modal", "reinstall-modal"): + assert element_id not in by_id + assert element_id not in script + + +def test_every_html_id_is_unique(page) -> None: + _, by_id = page + duplicates = sorted(element_id for element_id, elements in by_id.items() if len(elements) > 1) + assert duplicates == [] + + +def test_rescue_iso_pool_is_a_distinct_host_setting(page) -> None: + _, by_id = page + rescue_pool = by_id["host-rescue-iso-pool"][0] + assert rescue_pool.tag == "input" + assert rescue_pool.attrs["name"] == "rescue_iso_pool" + assert "required" not in rescue_pool.attrs # Existing installations can configure it later. + assert "host-form" in {ancestor.element_id for ancestor in rescue_pool.ancestors} + assert "rescue-templates-workspace" in { + ancestor.element_id for ancestor in by_id["rescue-directory-note"][0].ancestors + } + html = (STATIC_DIR / "index.html").read_text(encoding="utf-8") + assert "面板只注册已存在的目录,不会自动创建" in html + assert "不会出现在创建虚拟机的安装 ISO 列表中" in html + script = (STATIC_DIR / "app.js").read_text(encoding="utf-8") + assert 'byId("host-rescue-iso-pool").value = configured ? (hostConfig.rescue_iso_pool || "") : "";' in script + assert 'rescue_iso_pool: rescueIsoPool' in script + assert 'rescueIsoPool && rescueIsoPool === isoPool' in script + assert '"host-iso-pool", "host-rescue-iso-pool", "host-network"' in script + assert 'text("rescue-directory-note", rescueIsoPool' in script + + +def test_rescue_pages_are_separate_dashboard_pages(page) -> None: + _, by_id = page + rescue = by_id["rescue-view"][0] + assert {ancestor.element_id for ancestor in rescue.ancestors} >= { + "dashboard-view", "vm-workspace", + } + assert "hidden" in rescue.attrs + form = by_id["rescue-form"][0] + assert "rescue-view" in {ancestor.element_id for ancestor in form.ancestors} + assert "modal-backdrop" not in { + token + for ancestor in (*form.ancestors, form) + for token in (ancestor.attrs.get("class") or "").split() + } + + catalog = by_id["rescue-templates-workspace"][0] + assert "dashboard-view" in {ancestor.element_id for ancestor in catalog.ancestors} + assert "hidden" in catalog.attrs + upload = by_id["rescue-template-upload-form"][0] + assert "rescue-templates-workspace" in { + ancestor.element_id for ancestor in upload.ancestors + } + assert by_id["rescue-template-file"][0].attrs["type"] == "file" + + +def test_rescue_frontend_uses_streaming_upload_and_job_status(page) -> None: + _, by_id = page + assert by_id["rescue-templates-button"][0].tag == "button" + assert by_id["rescue-templates-mobile-button"][0].tag == "button" + script = (STATIC_DIR / "app.js").read_text(encoding="utf-8") + assert '"rescue-templates-button", "rescue-templates-mobile-button"' in script + assert 'rawBody: file, contentType: "application/octet-stream"' in script + assert "file.text()" not in script.split( + 'byId("rescue-template-upload-form").addEventListener', 1 + )[1].split("async function startRescueVmAction", 1)[0] + assert '"/api/v1/rescue-templates"' in script + assert '/rescue/exit`' in script + assert 'pollRescueImport(jobId' in script + assert 'pollVmRescueJob(jobId' in script + assert 'actionButton("紧急救援"' in script + assert 'const rescueMode = vm.rescue_mode === true;' in script + assert 'const rescueStaged = vm.rescue_staged === true;' in script + assert 'const rescueGuard = rescueMode || rescueStaged;' in script + assert 'typeof job.warning === "string"' in script + html = (STATIC_DIR / "index.html").read_text(encoding="utf-8") + assert "救援系统的登录方式和密码由该 ISO 自身决定" in html + + +def test_rescue_timeout_advises_manual_power_cycle_only_when_iso_is_staged(page) -> None: + _, by_id = page + assert "rescue-view" in by_id + script = (STATIC_DIR / "app.js").read_text(encoding="utf-8") + html = (STATIC_DIR / "index.html").read_text(encoding="utf-8") + assert "正常关机失败或超时" in html + assert "只有救援页显示“已预挂载”时" in html + assert "点击“强制重启进入救援”" in html + assert "强制断电并冷启动" in html + assert "“强制重置”不保证读取新保存的启动配置" in html + assert "若预挂载未成功,请先核查错误" in html + assert 'shutdownFailed && job.operation === "enter"' in script + assert 'shutdownFailed && job.operation === "exit"' in script + assert 'current?.staged === true && job.operation === "enter"' in script + assert 'state.rescueStaged = result?.staged === true;' in script + assert 'state.rescuePowerState = String(result?.power_state || "unknown");' in script + assert 'job.pending_manual_restart === true' in script + assert "正常关机失败或超时,救援 ISO 已预挂载但尚未进入救援系统" in script + assert '/rescue/force-start`' in script + assert 'ack_data_loss: true' in script + assert 'byId("rescue-force-start").addEventListener' in script + assert by_id["rescue-force-start"][0].attrs["type"] == "button" + assert 'disabled: busy || (rescueMode && !rescueStaged)' in script + assert 'title: rescueStaged ? "从已预挂载的救援 ISO 开机"' in script + assert "“强制重置”不保证读取新启动配置" in script + assert "面板不会自动强制断电" in script + assert 'else if (shuttingDown)' in script + assert '() => openConfirm(vm, "poweroff")' in script + assert "客服" not in html + assert "客服" not in script diff --git a/engine/tests/test_libvirt_service.py b/engine/tests/test_libvirt_service.py new file mode 100644 index 00000000..247fd980 --- /dev/null +++ b/engine/tests/test_libvirt_service.py @@ -0,0 +1,2287 @@ +"""Contract tests for the libvirt boundary; no hypervisor is required.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import pathlib +import sys +import tempfile +import types +import unittest +import uuid +import copy +import xml.etree.ElementTree as ET +from unittest.mock import patch + + +SERVICE_PATH = pathlib.Path(__file__).resolve().parents[1] / "virsh_panel" / "libvirt_service.py" +TEMPLATE_NAME = "panel-template-alma10-12345678-0123456789abcdef.qcow2" +RESCUE_NAME = "panel-rescue-0123456789abcdef0123456789abcdef.iso" + + +class FakeLibvirtError(Exception): + pass + + +class FakeVolume: + def __init__(self, pool, name, *, capacity=0, fmt="qcow2"): + self.pool = pool + self._name = name + self.capacity = capacity + self.format = fmt + self.contents = bytearray() + self.cloned_from = None + + def name(self): + return self._name + + def path(self): + return f"{self.pool.path}/{self._name}" + + def info(self): + return (0, self.capacity, len(self.contents), 0) + + def XMLDesc(self, flags): + assert flags == 0 + root = ET.Element("volume") + ET.SubElement(root, "name").text = self._name + ET.SubElement(root, "capacity", unit="bytes").text = str(self.capacity) + target = ET.SubElement(root, "target") + ET.SubElement(target, "format", type=self.format) + return ET.tostring(root, encoding="unicode") + + def resize(self, capacity, flags): + assert flags == 0 + assert capacity >= self.capacity + self.capacity = capacity + + def upload(self, stream, offset, length, flags): + assert offset == 0 and flags == 0 + if self.pool.backend.fail_upload: + raise FakeLibvirtError("upload failed") + stream.volume = self + stream.expected_length = length + self.contents.clear() + + def download(self, stream, offset, length, flags): + assert offset == 0 and flags == 0 + assert 0 <= length <= max(self.capacity, len(self.contents)) + stream.volume = self + stream.download_data = bytes(self.contents[:length]) + stream.read_offset = 0 + + def delete(self, flags): + assert flags == 0 + if self.pool.backend.fail_volume_delete: + raise FakeLibvirtError("volume delete failed") + self.pool.backend.deleted_volumes.append(self._name) + del self.pool.volumes[self._name] + + +class FakePool: + def __init__(self, backend, name, path, names=(), active=True, persistent=True, + pool_type="dir"): + self.backend = backend + self._name = name + self.path = path + self.volumes = {name: FakeVolume(self, name) for name in names} + self.external_names = set() + self.refreshes = 0 + self.active = active + self.persistent = persistent + self.pool_type = pool_type + self.auto_start = False + + def name(self): + return self._name + + def XMLDesc(self, flags): + assert flags == 0 + root = ET.Element("pool", type=self.pool_type) + ET.SubElement(root, "name").text = self._name + ET.SubElement(ET.SubElement(root, "target"), "path").text = self.path + return ET.tostring(root, encoding="unicode") + + def create(self, flags): + assert flags == 0 + if self.path not in self.backend.existing_dirs: + raise FakeLibvirtError("target directory missing") + self.active = True + self.backend.started.append(self._name) + + def setAutostart(self, enabled): + assert enabled == 1 + self.auto_start = True + self.backend.autostart_changed.append(self._name) + + def autostart(self): + return self.auto_start + + def isPersistent(self): + return self.persistent + + def destroy(self): + self.active = False + self.backend.destroyed.append(self._name) + + def undefine(self): + del self.backend.pools[self._name] + self.backend.undefined.append(self._name) + + def build(self, flags): + raise AssertionError("pool.build must not create host directories") + + def isActive(self): + return self.active + + def listVolumes(self): + return list(self.volumes) + + def refresh(self, flags): + assert flags == 0 + if not self.active: + raise FakeLibvirtError("pool is inactive") + self.refreshes += 1 + for name in self.external_names: + self.volumes.setdefault(name, FakeVolume(self, name)) + + def info(self): + return (2, 100 * 1024**3, 10 * 1024**3, 90 * 1024**3) + + def createXML(self, xml, flags): + assert flags == 0 + root = ET.fromstring(xml) + name = root.findtext("name") + fmt = root.find("./target/format").get("type") + assert fmt in ("qcow2", "raw") + if name in self.volumes or name in self.external_names: + raise FakeLibvirtError("volume exists") + capacity = int(root.findtext("capacity", "0")) + volume = FakeVolume(self, name, capacity=capacity, fmt=fmt) + self.volumes[name] = volume + return volume + + def createXMLFrom(self, xml, source_volume, flags): + assert flags == 0 + if self.backend.fail_clone: + raise FakeLibvirtError("clone failed") + assert source_volume.name() in self.volumes + volume = self.createXML(xml, 0) + volume.cloned_from = source_volume.name() + self.backend.clones.append((volume.name(), source_volume.name())) + return volume + + def storageVolLookupByName(self, name): + return self.volumes[name] + + +class FakeDomain: + def __init__(self, backend, xml, *, persistent=True, running=False): + self.backend = backend + root = self._parse_xml(xml) + self._uuid = root.findtext("uuid") + self.running = running + self.persistent = persistent + self.auto_start = False + self.live_root = root if running else None + self.inactive_root = copy.deepcopy(root) if persistent else None + self.snapshots = 0 + self.last_reset_flags = None + + @staticmethod + def _parse_xml(xml): + root = ET.fromstring(xml) + os_node = root.find("os") + if os_node is not None and os_node.get("firmware") == "efi" \ + and os_node.find("nvram") is None: + # libvirt adds an NVRAM image when it resolves firmware='efi'. + ET.SubElement(os_node, "nvram").text = ( + f"/var/lib/libvirt/qemu/nvram/{root.findtext('name')}_VARS.fd") + return root + + @property + def root(self): + # Compatibility for tests examining the VM's current configuration. + return self.live_root if self.running else self.inactive_root + + def define(self, xml): + root = self._parse_xml(xml) + assert root.findtext("uuid") == self._uuid + self.inactive_root = root + self.persistent = True + + def UUIDString(self): + return self._uuid + + def name(self): + return self.root.findtext("name") + + def info(self): + return (1 if self.running else 5, + int(self.root.findtext("memory")) * 1024, + int(self.root.findtext("memory")) * 1024, + int(self.root.findtext("vcpu")), 0) + + def blockInfo(self, identifier, flags): + assert flags == 0 + for disk in self.root.findall("./devices/disk[@device='disk']"): + source = disk.find("source") + target = disk.find("target") + path = source.get("file") if source is not None else None + if identifier not in (path, target.get("dev") if target is not None else None): + continue + for pool in self.backend.pools.values(): + for volume in pool.volumes.values(): + if volume.path() == path: + return (volume.capacity, len(volume.contents), volume.capacity) + raise FakeLibvirtError("block capacity unavailable") + + def XMLDesc(self, flags): + assert flags in (0, 1) + if flags == 1: + if not self.persistent: + raise FakeLibvirtError("transient domain has no inactive XML") + xml_root = copy.deepcopy(self.inactive_root) + else: + xml_root = copy.deepcopy(self.root) + graphics = xml_root.find("./devices/graphics") + if graphics is not None: + graphics.set("port", "5907" if self.running and flags == 0 else "-1") + return ET.tostring(xml_root, encoding="unicode") + + def autostart(self): + return int(self.auto_start) + + def setAutostart(self, enabled): + assert enabled in (0, 1) + if not self.persistent or self.backend.fail_domain_autostart: + raise FakeLibvirtError("domain autostart failed") + self.auto_start = bool(enabled) + self.backend.domain_autostart_changed.append(self._uuid) + + def isActive(self): + return self.running + + def isPersistent(self): + return self.persistent + + def create(self): + if not self.persistent: + raise FakeLibvirtError("cannot start a stopped transient domain") + if self.backend.fail_domain_create: + raise FakeLibvirtError("domain create failed") + interface = self.inactive_root.find("./devices/interface") + if (interface is not None and interface.get("type") == "bridge" + and not self.backend.bridge_active): + raise FakeLibvirtError("bridge does not exist") + self.live_root = copy.deepcopy(self.inactive_root) + self.running = True + self.backend.domain_starts += 1 + if self.backend.fail_domain_create_after_start: + raise FakeLibvirtError("transport failed after domain started") + + def guest_reboot(self): + """Simulate a reboot initiated by an installer inside the guest.""" + assert self.running + if self.live_root.findtext("on_reboot") == "destroy": + self.running = False + self.live_root = None + if not self.persistent: + self.backend.domains.remove(self) + + def shutdown(self): + self.backend.shutdown_calls += 1 + if self.backend.shutdown_stalls: + return + self.running = False + self.live_root = None + if not self.persistent: + self.backend.domains.remove(self) + + def reboot(self): + assert self.running + self.guest_reboot() + + def destroy(self): + if self.backend.fail_destroy: + raise FakeLibvirtError("domain destroy failed") + self.backend.destroy_calls += 1 + self.running = False + self.live_root = None + if not self.persistent: + self.backend.domains.remove(self) + + def reset(self, flags): + self.last_reset_flags = flags + + def snapshotNum(self, flags): + return self.snapshots + + def hasManagedSaveImage(self, flags): + assert flags == 0 + return 0 + + def undefineFlags(self, flags): + assert flags in (4, 8) + if self.backend.fail_undefine: + raise FakeLibvirtError("domain undefine failed") + self.backend.undefine_flags.append(flags) + self.persistent = False + self.backend.domains.remove(self) + + def undefine(self): + if self.backend.fail_undefine: + raise FakeLibvirtError("domain undefine failed") + if self.root.find("./os/nvram") is not None: + raise FakeLibvirtError("UEFI domain requires an NVRAM undefine flag") + self.persistent = False + self.backend.domains.remove(self) + + +class FakeConnection: + def __init__(self, backend): + self.backend = backend + + def close(self): + self.backend.closed += 1 + + def listAllDomains(self, flags): + assert flags == 0 + return list(self.backend.domains) + + def getInfo(self): + return ("x86_64", 0, 0, 0, 0, 0, 0, 0) + + def storagePoolLookupByName(self, name): + try: + return self.backend.pools[name] + except KeyError as exc: + raise FakeLibvirtError("pool not found") from exc + + def listAllStoragePools(self, flags): + assert flags == 0 + return list(self.backend.pools.values()) + + def storagePoolDefineXML(self, xml, flags): + assert flags == 0 + root = ET.fromstring(xml) + assert root.get("type") == "dir" + name = root.findtext("name") + path = root.findtext("./target/path") + if name in self.backend.pools: + raise FakeLibvirtError("pool name already exists") + pool = FakePool(self.backend, name, path, active=False) + self.backend.pools[name] = pool + self.backend.defined.append((name, path)) + return pool + + def networkLookupByName(self, name): + assert name == self.backend.network_name + self.backend.network_lookups.append(name) + return types.SimpleNamespace(isActive=lambda: self.backend.network_active) + + def defineXML(self, xml): + if self.backend.fail_define: + raise FakeLibvirtError("define failed") + root = ET.fromstring(xml) + self.backend.define_xmls.append(root) + vm_uuid = root.findtext("uuid") + for domain in self.backend.domains: + if domain.UUIDString() == vm_uuid: + domain.define(xml) + return domain + domain = FakeDomain(self.backend, xml) + self.backend.domains.append(domain) + return domain + + def createXML(self, xml, flags): + assert flags == 0 + if self.backend.fail_create: + raise FakeLibvirtError("createXML failed") + root = ET.fromstring(xml) + self.backend.create_xmls.append(root) + interface = root.find("./devices/interface") + if (interface is not None and interface.get("type") == "bridge" + and not self.backend.bridge_active): + raise FakeLibvirtError("bridge does not exist") + domain = FakeDomain(self.backend, xml, persistent=False, running=True) + self.backend.domains.append(domain) + return domain + + def newStream(self, flags): + assert flags == 0 + stream = FakeStream(self.backend) + self.backend.streams.append(stream) + return stream + + +class FakeStream: + def __init__(self, backend): + self.backend = backend + self.volume = None + self.expected_length = None + self.finished = False + self.aborted = False + self.download_data = None + self.read_offset = 0 + + def send(self, data): + if self.backend.fail_send: + raise FakeLibvirtError("stream send failed") + assert self.volume is not None + self.volume.contents.extend(data) + return len(data) + + def finish(self): + assert self.volume is not None + if self.download_data is None: + assert len(self.volume.contents) == self.expected_length + else: + assert self.read_offset == len(self.download_data) + self.finished = True + + def recv(self, length): + assert self.download_data is not None + assert length > 0 + chunk = self.download_data[self.read_offset:self.read_offset + length] + self.read_offset += len(chunk) + return chunk + + def abort(self): + self.aborted = True + + +class FakeBackend: + def __init__(self): + self.domains = [] + self.existing_dirs = { + "/var/lib/libvirt/images", "/var/lib/libvirt/iso", + "/home/kvm", "/home/iso", "/home/rescue", + } + self.pools = { + "images": FakePool(self, "images", "/var/lib/libvirt/images"), + "iso": FakePool(self, "iso", "/var/lib/libvirt/iso", + ("AlmaLinux-10.iso", "notes.txt")), + } + self.defined = [] + self.started = [] + self.autostart_changed = [] + self.domain_autostart_changed = [] + self.destroyed = [] + self.undefined = [] + self.undefine_flags = [] + self.create_xmls = [] + self.define_xmls = [] + self.clones = [] + self.deleted_volumes = [] + self.domain_starts = 0 + self.shutdown_calls = 0 + self.destroy_calls = 0 + self.shutdown_stalls = False + self.streams = [] + self.network_active = True + self.network_name = "default" + self.network_lookups = [] + self.bridge_active = True + self.fail_define = False + self.fail_create = False + self.fail_domain_create = False + self.fail_domain_create_after_start = False + self.fail_domain_autostart = False + self.fail_destroy = False + self.fail_undefine = False + self.fail_volume_delete = False + self.fail_clone = False + self.fail_upload = False + self.fail_send = False + self.opened = 0 + self.closed = 0 + + def open(self, uri): + assert uri == "qemu+ssh://panel@hypervisor/system" + self.opened += 1 + return FakeConnection(self) + + +class VMServiceTests(unittest.TestCase): + def setUp(self): + self.backend = FakeBackend() + fake_libvirt = types.ModuleType("libvirt") + fake_libvirt.libvirtError = FakeLibvirtError + fake_libvirt.VIR_DOMAIN_UNDEFINE_NVRAM = 4 + fake_libvirt.VIR_DOMAIN_UNDEFINE_KEEP_NVRAM = 8 + fake_libvirt.VIR_DOMAIN_XML_INACTIVE = 1 + fake_libvirt.open = self.backend.open + module_spec = importlib.util.spec_from_file_location("service_under_test", SERVICE_PATH) + self.assertIsNotNone(module_spec) + module = importlib.util.module_from_spec(module_spec) + with patch.dict(sys.modules, {"libvirt": fake_libvirt}): + module_spec.loader.exec_module(module) + self.service_module = module + self.service = module.VMService( + "qemu+ssh://panel@hypervisor/system", "images", "iso", "default", + rescue_iso_pool="/home/rescue") + self.error_type = module.VMError + + @staticmethod + def spec(**changes): + data = { + "name": "alma-test", + "vcpu": 2, + "memory_mib": 2048, + "disk_gib": 20, + "network": "default", + "iso": "AlmaLinux-10.iso", + } + data.update(changes) + return data + + def test_package_bandwidth_is_enforced_both_directions(self): + spec = self.service._validate_create(self.spec(bandwidth_mbps=100)) + xml = self.service._domain_xml(spec, "00000000-0000-4000-8000-000000000001", + "alma-test.qcow2", ("file", {"file": "/home/kvm/alma-test.qcow2"}), + ("file", {"file": "/home/iso/AlmaLinux-10.iso"}), install_phase=True) + root = ET.fromstring(xml) + for direction in ("inbound", "outbound"): + limiter = root.find(f"./devices/interface/bandwidth/{direction}") + self.assertEqual(limiter.get("average"), "12208") + self.assertEqual(limiter.get("peak"), "12208") + cloud_xml = self.service._cloud_domain_xml(spec, "00000000-0000-4000-8000-000000000001", + "alma-test.qcow2", ("file", {"file": "/home/kvm/alma-test.qcow2"}), + "panel-seed.iso", ("file", {"file": "/home/kvm/panel-seed.iso"}), + "52:54:00:12:34:56", "8.8.8.18/24") + self.assertIsNotNone(ET.fromstring(cloud_xml).find("./devices/interface/bandwidth")) + + def test_invalid_package_bandwidth_is_rejected(self): + for value in (0, -1, 100001, True, "100"): + with self.subTest(value=value), self.assertRaises(self.error_type): + self.service._validate_create(self.spec(bandwidth_mbps=value)) + + @staticmethod + def cloud_spec(**changes): + # Public examples are used only as parser fixtures; these addresses + # must never be assumed to belong to a real panel deployment. + data = { + "source": "cloud", + "name": "cloud-vm", + "vcpu": 4, + "memory_mib": 4096, + "disk_gib": 20, + "network": "bridge:br0", + "public_ip_cidr": "8.8.8.18/24", + "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1", "8.8.8.8"], + "guest_ssh_public_key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 panel-test", + } + data.update(changes) + return data + + def cloud_service(self): + self.backend.pools["images"].volumes[TEMPLATE_NAME] = FakeVolume( + self.backend.pools["images"], TEMPLATE_NAME, + capacity=2 * 1024**3, + ) + return self.service.__class__( + self.service.uri, "images", "iso", "bridge:br0", + rescue_iso_pool="/home/rescue", + ) + + def create_cloud_vm(self, service, spec): + # Exercise the remote libvirt orchestration without requiring the + # optional ISO writer on test hosts. test_cloud_init.py checks the + # real generated ISO separately when pycdlib is available. + with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED", create=True): + return service.create_cloud_vm(spec, TEMPLATE_NAME) + + def cloud_vm_with_real_seed(self): + """Create a cloud VM and replace its stub seed with real NoCloud data.""" + if importlib.util.find_spec("pycdlib") is None: + self.skipTest("pycdlib is not installed") + from virsh_panel.cloud_init import build_seed_iso, validate_cloud_network + + service = self.cloud_service() + spec = self.cloud_spec() + created = self.create_cloud_vm(service, spec) + domain = self.backend.domains[0] + root = domain.root + metadata = root.find(f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + seed_name = metadata.get("seed-volume") + mac = root.find("./devices/interface/mac").get("address") + network = validate_cloud_network( + spec["public_ip_cidr"], spec["gateway"], spec["dns_servers"], + spec["guest_ssh_public_key"], + ) + seed_data = build_seed_iso(created["uuid"], spec["name"], mac, network) + seed = self.backend.pools["images"].volumes[seed_name] + seed.contents = bytearray(seed_data) + seed.capacity = len(seed_data) + return service, created, spec, domain, seed_name + + def test_create_list_resources_and_console(self): + resources = self.service.resources() + self.assertEqual(resources["networks"], ["default"]) + self.assertEqual(resources["isos"], ["AlmaLinux-10.iso"]) + vm = self.service.create_vm(self.spec()) + self.assertEqual(vm["state"], "running") + self.assertTrue(vm["autostart"]) + self.assertEqual(self.backend.domain_autostart_changed, [vm["uuid"]]) + self.assertEqual(vm["vcpu"], 2) + self.assertEqual(vm["memory_mib"], 2048) + self.assertRegex(vm["created_at"], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") + self.assertEqual(len(vm["disks"]), 1) + self.assertEqual(vm["disks"][0]["source"], + "/var/lib/libvirt/images/alma-test.qcow2") + self.assertEqual(vm["disks"][0]["capacity_gib"], 20) + self.assertTrue(vm["managed"]) + self.assertEqual(vm["console_port"], 5907) + self.assertEqual(self.service.console_port(vm["uuid"]), 5907) + self.assertEqual(self.service.list_vms()[0]["uuid"], vm["uuid"]) + self.assertEqual(self.service.get_vm(vm["uuid"])["name"], "alma-test") + disk_name = "alma-test.qcow2" + self.assertIn(disk_name, self.backend.pools["images"].volumes) + root = self.backend.domains[0].root + self.assertEqual(root.find("./devices/disk[@device='disk']").get("type"), "file") + self.assertEqual(root.find("./devices/disk[@device='cdrom']").get("type"), "file") + self.assertEqual(root.find("./devices/graphics").get("listen"), "127.0.0.1") + self.assertEqual( + [boot.get("dev") for boot in root.findall("./os/boot")], + ["cdrom", "hd"], + ) + self.assertEqual(root.findtext("on_reboot"), "destroy") + final_root = self.backend.domains[0].inactive_root + self.assertEqual(root.find("./metadata/{urn:virsh-panel:1}managed").get("created-at"), + vm["created_at"]) + self.assertEqual(final_root.find("./metadata/{urn:virsh-panel:1}managed").get("created-at"), + vm["created_at"]) + self.assertEqual([boot.get("dev") for boot in final_root.findall("./os/boot")], + ["hd"]) + self.assertIsNone(final_root.find("./devices/disk[@device='cdrom']/source")) + self.assertEqual(len(self.backend.create_xmls), 1) + self.assertEqual(len(self.backend.define_xmls), 1) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_iso_create_accepts_preassigned_uuid_for_user_ownership(self): + requested_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4" + created = self.service.create_vm(self.spec(vm_uuid=requested_uuid)) + self.assertEqual(created["uuid"], requested_uuid) + self.assertEqual(self.backend.domains[0].root.findtext("uuid"), requested_uuid) + with self.assertRaisesRegex(self.error_type, "UUID"): + self.service.create_vm(self.spec(name="invalid-uuid", vm_uuid="not-a-uuid")) + + def test_unmanaged_vm_does_not_claim_an_os_or_ip(self): + vm = self.service.create_vm(self.spec()) + domain = self.backend.domains[0] + for root in (domain.live_root, domain.inactive_root): + root.remove(root.find("metadata")) + listed = self.service.get_vm(vm["uuid"]) + self.assertFalse(listed["managed"]) + self.assertIsNone(listed["os_name"]) + self.assertEqual(listed["os_source"], "unknown") + self.assertIsNone(listed["install_iso"]) + self.assertIsNone(listed["public_ip_cidr"]) + self.assertIsNone(listed["created_at"]) + + def test_older_panel_vm_without_creation_marker_has_unknown_time(self): + vm = self.service.create_vm(self.spec()) + domain = self.backend.domains[0] + for root in (domain.live_root, domain.inactive_root): + root.find("./metadata/{urn:virsh-panel:1}managed").attrib.pop("created-at") + self.assertIsNone(self.service.get_vm(vm["uuid"])["created_at"]) + + def test_installer_reboot_stops_guest_and_next_start_uses_unmounted_iso(self): + vm = self.service.create_vm(self.spec()) + domain = self.backend.domains[0] + self.assertTrue(domain.autostart()) + install_root = ET.fromstring(domain.XMLDesc(0)) + final_root = ET.fromstring(domain.XMLDesc(1)) + self.assertEqual(install_root.findtext("on_reboot"), "destroy") + self.assertIsNotNone(install_root.find("./devices/disk[@device='cdrom']/source")) + self.assertIsNone(final_root.find("./devices/disk[@device='cdrom']/source")) + self.assertEqual(domain.UUIDString(), vm["uuid"]) + self.assertEqual(install_root.findtext("./os/nvram"), + final_root.findtext("./os/nvram")) + + domain.guest_reboot() + self.assertFalse(domain.isActive()) + self.assertTrue(domain.autostart()) + self.assertTrue(domain.isPersistent()) + self.assertEqual(len(self.backend.domains), 1) + self.assertEqual(self.service.get_vm(vm["uuid"])["state"], "shutoff") + self.assertEqual(self.service.action(vm["uuid"], "start")["state"], "running") + booted_root = ET.fromstring(domain.XMLDesc(0)) + self.assertEqual([boot.get("dev") for boot in booted_root.findall("./os/boot")], + ["hd"]) + self.assertIsNone(booted_root.find("./devices/disk[@device='cdrom']/source")) + self.assertIsNone(booted_root.find("on_reboot")) + self.assertEqual(booted_root.findtext("uuid"), vm["uuid"]) + self.assertEqual(booted_root.findtext("./os/nvram"), + install_root.findtext("./os/nvram")) + self.assertEqual(self.service.console_port(vm["uuid"]), 5907) + + def test_create_matches_original_virt_install_with_configured_directories(self): + disk_pool = self.backend.pools["images"] + iso_pool = self.backend.pools["iso"] + disk_pool.path = "/home/kvm" + iso_pool.path = "/home/iso" + iso_name = "AlmaLinux-10.1-x86_64-minimal.iso" + iso_pool.volumes[iso_name] = FakeVolume(iso_pool, iso_name) + service = self.service.__class__( + self.service.uri, "/home/kvm", "/home/iso", "bridge:br0") + self.assertEqual(service.ensure_storage_pools(), + {"storage_pool": "images", "iso_pool": "iso"}) + spec = self.spec(name="web", memory_mib=2042, vcpu=8, disk_gib=100, + network="bridge:br0", iso=iso_name) + with patch.object(disk_pool, "info", return_value=( + 2, 200 * 1024**3, 10 * 1024**3, 190 * 1024**3)): + vm = service.create_vm(spec) + + root = self.backend.domains[0].root + self.assertEqual(vm["state"], "running") + self.assertEqual(root.findtext("name"), "web") + self.assertEqual(root.find("memory").attrib, {"unit": "MiB"}) + self.assertEqual(root.findtext("memory"), "2042") + self.assertEqual(root.findtext("vcpu"), "8") + self.assertEqual(root.find("cpu").get("mode"), "host-passthrough") + self.assertEqual(root.find("os").get("firmware"), "efi") + self.assertEqual(root.findtext("./os/type"), "hvm") + self.assertEqual(root.find("./os/type").get("machine"), "q35") + self.assertIsNotNone(root.find("./features/acpi")) + self.assertIsNotNone(root.find("./features/apic")) + self.assertEqual([node.get("dev") for node in root.findall("./os/boot")], + ["cdrom", "hd"]) + self.assertEqual(root.findtext("on_reboot"), "destroy") + final_root = self.backend.domains[0].inactive_root + self.assertEqual([node.get("dev") for node in final_root.findall("./os/boot")], + ["hd"]) + self.assertIsNone(final_root.find("./devices/disk[@device='cdrom']/source")) + self.assertEqual(final_root.findtext("./os/nvram"), root.findtext("./os/nvram")) + self.assertEqual(final_root.findtext("uuid"), root.findtext("uuid")) + self.assertEqual(final_root.find("./devices/disk[@device='disk']/source").attrib, + root.find("./devices/disk[@device='disk']/source").attrib) + + disk = root.find("./devices/disk[@device='disk']") + self.assertEqual(disk.get("type"), "file") + self.assertEqual(disk.find("driver").attrib, { + "name": "qemu", "type": "qcow2", "cache": "none", "discard": "unmap", + }) + self.assertEqual(disk.find("source").attrib, + {"file": "/home/kvm/web.qcow2"}) + self.assertEqual(disk.find("target").attrib, + {"dev": "vda", "bus": "virtio"}) + cdrom = root.find("./devices/disk[@device='cdrom']") + self.assertEqual(cdrom.get("type"), "file") + self.assertEqual(cdrom.find("source").attrib, + {"file": f"/home/iso/{iso_name}"}) + self.assertIsNotNone(cdrom.find("readonly")) + + interface = root.find("./devices/interface") + self.assertEqual(interface.get("type"), "bridge") + self.assertEqual(interface.find("source").attrib, {"bridge": "br0"}) + self.assertEqual(interface.find("model").attrib, {"type": "virtio"}) + self.assertEqual(interface.find("driver").attrib, {"queues": "8"}) + graphics = root.find("./devices/graphics") + self.assertEqual(graphics.get("type"), "vnc") + self.assertEqual(graphics.get("listen"), "127.0.0.1") + self.assertEqual(graphics.get("port"), "-1") + self.assertEqual(graphics.get("autoport"), "yes") + self.assertEqual(graphics.find("listen").attrib, + {"type": "address", "address": "127.0.0.1"}) + self.assertNotIn("passwd", graphics.attrib) + + channel = root.find("./devices/channel/target[@name='org.qemu.guest_agent.0']") + self.assertIsNotNone(channel) + self.assertEqual(channel.get("type"), "virtio") + balloon = root.find("./devices/memballoon") + self.assertEqual(balloon.get("model"), "virtio") + self.assertEqual(balloon.get("freePageReporting"), "on") + self.assertGreater(int(balloon.find("stats").get("period")), 0) + self.assertEqual(root.find("./metadata/{urn:virsh-panel:1}managed").attrib, + {"version": "2", "disk-volume": "web.qcow2", + "os-source": "iso", "install-iso": iso_name, + "created-at": vm["created_at"]}) + self.assertIsNone(vm["os_name"]) + self.assertEqual(vm["os_source"], "iso") + self.assertEqual(vm["install_iso"], iso_name) + + service.action(vm["uuid"], "shutdown") + self.assertEqual(service.delete_vm(vm["uuid"], True)["deleted_disks"], + ["web.qcow2"]) + self.assertEqual(self.backend.undefine_flags, [4]) + self.assertNotIn("web.qcow2", disk_pool.volumes) + + def test_linux_bridge_uses_host_bridge_xml_not_libvirt_network(self): + service = self.service.__class__(self.service.uri, "images", "iso", "bridge:br0") + self.assertEqual(service.resources()["networks"], ["bridge:br0"]) + self.assertEqual(self.backend.network_lookups, []) + vm = service.create_vm(self.spec(network="bridge:br0")) + self.assertEqual(vm["state"], "running") + interface = self.backend.domains[0].root.find("./devices/interface") + self.assertEqual(interface.get("type"), "bridge") + self.assertEqual(interface.find("source").attrib, {"bridge": "br0"}) + self.assertEqual(self.backend.network_lookups, []) + + def test_bare_br0_remains_a_libvirt_virtual_network_name(self): + self.backend.network_name = "br0" + service = self.service.__class__(self.service.uri, "images", "iso", "br0") + self.assertEqual(service.resources()["networks"], ["br0"]) + service.create_vm(self.spec(network="br0")) + interface = self.backend.domains[0].root.find("./devices/interface") + self.assertEqual(interface.get("type"), "network") + self.assertEqual(interface.find("source").attrib, {"network": "br0"}) + self.assertEqual(self.backend.network_lookups, ["br0", "br0"]) + + def test_virtio_net_queues_follow_vcpu_up_to_sixteen_for_both_network_modes(self): + for network in ("default", "bridge:br0"): + service = self.service.__class__(self.service.uri, "images", "iso", network) + for vcpu, expected_queues in ((1, 1), (8, 8), (32, 16)): + with self.subTest(network=network, vcpu=vcpu): + service.create_vm(self.spec( + name=f"alma-{network.replace(':', '-')}-{vcpu}", + network=network, vcpu=vcpu, + )) + interface = self.backend.domains[-1].root.find("./devices/interface") + self.assertEqual(interface.find("model").attrib, {"type": "virtio"}) + self.assertEqual(interface.find("driver").attrib, { + "queues": str(expected_queues), + }) + + def test_missing_host_bridge_rolls_back_domain_and_disk(self): + self.backend.bridge_active = False + service = self.service.__class__(self.service.uri, "images", "iso", "bridge:br0") + with self.assertRaises(self.error_type) as error: + service.create_vm(self.spec(network="bridge:br0")) + self.assertEqual(error.exception.status, 409) + self.assertIn("br0", str(error.exception)) + self.assertFalse(self.backend.domains) + self.assertFalse(self.backend.pools["images"].volumes) + self.assertEqual(self.backend.undefine_flags, []) + + def test_invalid_bridge_selector_rejected_before_connection(self): + for selector in ("bridge:", "bridge:br/0", "bridge:br 0", + "bridge:" + "a" * 16, "bridge:-br0"): + with self.subTest(selector=selector), self.assertRaises(ValueError): + self.service.__class__(self.service.uri, "images", "iso", selector) + self.assertEqual(self.backend.opened, 0) + + def test_directory_paths_reuse_existing_pools_and_domain_uses_files(self): + self.backend.pools["images"].path = "/home/kvm" + self.backend.pools["iso"].path = "/home/iso" + service = self.service.__class__(self.service.uri, "/home/kvm", "/home/iso", "default") + self.assertEqual(service.ensure_storage_pools(), + {"storage_pool": "images", "iso_pool": "iso"}) + self.assertEqual(self.backend.defined, []) + self.assertEqual(service.resources()["isos"], ["AlmaLinux-10.iso"]) + vm = service.create_vm(self.spec()) + disk = self.backend.domains[0].root.find("./devices/disk[@device='disk']/source") + cdrom = self.backend.domains[0].root.find("./devices/disk[@device='cdrom']/source") + self.assertEqual(disk.attrib, {"file": "/home/kvm/alma-test.qcow2"}) + self.assertEqual(cdrom.attrib, {"file": "/home/iso/AlmaLinux-10.iso"}) + service.action(vm["uuid"], "shutdown") + self.assertEqual(len(service.delete_vm(vm["uuid"], True)["deleted_disks"]), 1) + + def test_directory_paths_are_defined_only_by_explicit_ensure(self): + service = self.service.__class__(self.service.uri, "/home/kvm", "/home/iso", "default") + with self.assertRaises(self.error_type) as missing: + service.resources() + self.assertEqual(missing.exception.status, 409) + self.assertEqual(self.backend.defined, []) + + names = service.ensure_storage_pools() + self.assertEqual([path for _, path in self.backend.defined], + ["/home/kvm", "/home/iso"]) + self.assertTrue(names["storage_pool"].startswith("panel-dir-")) + self.assertNotEqual(names["storage_pool"], names["iso_pool"]) + self.assertTrue(self.backend.pools[names["storage_pool"]].autostart()) + self.assertTrue(self.backend.pools[names["iso_pool"]].autostart()) + self.assertEqual(service.ensure_storage_pools(), names) + self.assertEqual(len(self.backend.defined), 2) + self.assertEqual(len(self.backend.autostart_changed), 2) + + iso_pool = self.backend.pools[names["iso_pool"]] + iso_pool.volumes["AlmaLinux-10.iso"] = FakeVolume(iso_pool, "AlmaLinux-10.iso") + vm = service.create_vm(self.spec()) + disk = self.backend.domains[0].root.find("./devices/disk[@device='disk']/source") + cdrom = self.backend.domains[0].root.find("./devices/disk[@device='cdrom']/source") + self.assertEqual(disk.attrib, {"file": "/home/kvm/alma-test.qcow2"}) + self.assertEqual(cdrom.attrib, {"file": "/home/iso/AlmaLinux-10.iso"}) + service.action(vm["uuid"], "shutdown") + self.assertEqual(len(service.delete_vm(vm["uuid"], True)["deleted_disks"]), 1) + + def test_missing_directory_does_not_leave_a_pool_definition(self): + service = self.service.__class__(self.service.uri, "/home/missing", "iso", "default") + with self.assertRaises(self.error_type) as missing: + service.ensure_storage_pools() + self.assertEqual(missing.exception.status, 409) + self.assertIn("/home/missing", str(missing.exception)) + self.assertEqual(self.backend.defined[0][1], "/home/missing") + self.assertEqual(set(self.backend.pools), {"images", "iso"}) + + def test_iso_failure_rolls_back_new_disk_pool_but_not_host_directories(self): + original_directories = set(self.backend.existing_dirs) + service = self.service.__class__( + self.service.uri, "/home/kvm", "/home/missing-iso", "default") + with self.assertRaises(self.error_type) as missing: + service.ensure_storage_pools() + self.assertEqual(missing.exception.status, 409) + self.assertIn("/home/missing-iso", str(missing.exception)) + self.assertEqual(set(self.backend.pools), {"images", "iso"}) + self.assertEqual(self.backend.existing_dirs, original_directories) + self.assertEqual(len(self.backend.defined), 2) + self.assertEqual(set(self.backend.undefined), + {name for name, _ in self.backend.defined}) + self.assertEqual(self.backend.destroyed, [self.backend.defined[0][0]]) + + def test_iso_failure_does_not_undefine_preexisting_disk_pool(self): + self.backend.pools["images"].path = "/home/kvm" + service = self.service.__class__( + self.service.uri, "/home/kvm", "/home/missing-iso", "default") + with self.assertRaises(self.error_type): + service.ensure_storage_pools() + self.assertIn("images", self.backend.pools) + self.assertEqual(self.backend.pools["images"].path, "/home/kvm") + self.assertNotIn("images", self.backend.undefined) + self.assertNotIn("images", self.backend.destroyed) + + def test_directory_pool_validation_and_existing_inactive_pool(self): + for invalid in ("/", "/home/../etc", "//home/kvm", "/home/./kvm"): + with self.subTest(invalid=invalid), self.assertRaises(self.error_type): + self.service.__class__(self.service.uri, invalid, "iso", "default").ensure_storage_pools() + self.backend.pools["images"].path = "/home/kvm" + self.backend.pools["images"].active = False + service = self.service.__class__(self.service.uri, "/home/kvm/", "iso", "default") + self.assertEqual(service.ensure_storage_pools()["storage_pool"], "images") + self.assertIn("images", self.backend.started) + self.assertTrue(self.backend.pools["images"].autostart()) + self.assertEqual(self.backend.autostart_changed, ["images", "iso"]) + self.assertEqual(service.ensure_storage_pools()["storage_pool"], "images") + self.assertEqual(self.backend.started, ["images"]) + self.assertEqual(self.backend.autostart_changed, ["images", "iso"]) + + def test_transient_existing_pool_rejected_without_changes(self): + self.backend.pools["images"].path = "/home/kvm" + self.backend.pools["images"].persistent = False + service = self.service.__class__(self.service.uri, "/home/kvm", "iso", "default") + with self.assertRaises(self.error_type) as transient: + service.ensure_storage_pools() + self.assertEqual(transient.exception.status, 409) + self.assertEqual(self.backend.defined, []) + self.assertEqual(self.backend.started, []) + self.assertEqual(self.backend.autostart_changed, []) + + def test_directory_pool_name_collision_is_not_overwritten(self): + service = self.service.__class__(self.service.uri, "/home/kvm", "iso", "default") + generated_name = "panel-dir-" + hashlib.sha256(b"/home/kvm").hexdigest()[:48] + self.backend.pools[generated_name] = FakePool( + self.backend, generated_name, "/home/somewhere-else") + with self.assertRaises(self.error_type) as collision: + service.ensure_storage_pools() + self.assertEqual(collision.exception.status, 409) + self.assertEqual(self.backend.defined, []) + self.assertEqual(self.backend.pools[generated_name].path, "/home/somewhere-else") + + def test_console_requires_loopback_vnc_listener(self): + vm = self.service.create_vm(self.spec()) + graphics = self.backend.domains[0].root.find("./devices/graphics") + graphics.set("listen", "0.0.0.0") + with self.assertRaises(self.error_type) as exposed: + self.service.console_port(vm["uuid"]) + self.assertEqual(exposed.exception.status, 409) + + def test_validation_happens_before_creating_resources(self): + for spec in (self.spec(name="../../escape"), self.spec(vcpu=True), + self.spec(memory_mib=128), self.spec(network="other"), + self.spec(iso="../bad.iso")): + with self.subTest(spec=spec), self.assertRaises(self.error_type): + self.service.create_vm(spec) + self.assertFalse(self.backend.pools["images"].volumes) + + def test_unavailable_iso_and_define_failure_leave_no_disk(self): + with self.assertRaises(self.error_type) as missing: + self.service.create_vm(self.spec(iso="missing.iso")) + self.assertEqual(missing.exception.status, 404) + self.backend.fail_define = True + with self.assertRaises(self.error_type) as define_error: + self.service.create_vm(self.spec()) + self.assertEqual(define_error.exception.status, 502) + self.assertIn("卸载 ISO 后的配置", str(define_error.exception)) + self.assertFalse(self.backend.pools["images"].volumes) + self.assertFalse(self.backend.domains) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_create_xml_failure_leaves_no_domain_or_disk(self): + self.backend.fail_create = True + with self.assertRaises(self.error_type) as start_error: + self.service.create_vm(self.spec()) + self.assertEqual(start_error.exception.status, 409) + self.assertFalse(self.backend.domains) + self.assertFalse(self.backend.pools["images"].volumes) + self.assertEqual(self.backend.create_xmls, []) + self.assertEqual(self.backend.define_xmls, []) + self.assertEqual(self.backend.undefine_flags, []) + + def test_final_define_failure_destroys_transient_guest_and_disk(self): + self.backend.fail_define = True + with self.assertRaises(self.error_type): + self.service.create_vm(self.spec()) + self.assertEqual(len(self.backend.create_xmls), 1) + self.assertEqual(self.backend.define_xmls, []) + self.assertFalse(self.backend.domains) + self.assertFalse(self.backend.pools["images"].volumes) + self.assertEqual(self.backend.undefine_flags, []) + + def test_iso_vm_autostart_failure_rolls_back_new_vm_and_disk(self): + self.backend.fail_domain_autostart = True + with self.assertRaises(self.error_type) as failure: + self.service.create_vm(self.spec()) + self.assertEqual(failure.exception.status, 502) + self.assertIn("开机自启", str(failure.exception)) + self.assertFalse(self.backend.domains) + self.assertFalse(self.backend.pools["images"].volumes) + self.assertEqual(self.backend.domain_autostart_changed, []) + + def test_final_define_failure_preserves_disk_referenced_by_other_live_vm(self): + other = self.service.create_vm(self.spec(name="other-vm")) + other_domain = self.backend.domains[0] + new_disk_path = "/var/lib/libvirt/images/alma-test.qcow2" + + def fail_after_external_attach(conn, xml): + other_domain.live_root.find("./devices/disk[@device='disk']/source").attrib = { + "file": new_disk_path, + } + raise FakeLibvirtError("define failed after external disk attach") + + with patch.object(FakeConnection, "defineXML", fail_after_external_attach): + with self.assertRaises(self.error_type) as incomplete: + self.service.create_vm(self.spec()) + + self.assertEqual(incomplete.exception.status, 502) + self.assertEqual(len(self.backend.domains), 1) + self.assertEqual(self.backend.domains[0].UUIDString(), other["uuid"]) + self.assertTrue(other_domain.isActive()) + self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) + + def test_final_define_failure_preserves_disk_referenced_only_by_inactive_xml(self): + other = self.service.create_vm(self.spec(name="other-vm")) + other_domain = self.backend.domains[0] + original_live_source = other_domain.live_root.find( + "./devices/disk[@device='disk']/source").get("file") + new_disk_path = "/var/lib/libvirt/images/alma-test.qcow2" + + def fail_after_external_config_change(conn, xml): + other_domain.inactive_root.find( + "./devices/disk[@device='disk']/source").attrib = { + "file": new_disk_path, + } + raise FakeLibvirtError("define failed after external config change") + + with patch.object(FakeConnection, "defineXML", fail_after_external_config_change): + with self.assertRaises(self.error_type) as incomplete: + self.service.create_vm(self.spec()) + + self.assertEqual(incomplete.exception.status, 502) + self.assertEqual(len(self.backend.domains), 1) + self.assertEqual(self.backend.domains[0].UUIDString(), other["uuid"]) + self.assertEqual(other_domain.live_root.find( + "./devices/disk[@device='disk']/source").get("file"), original_live_source) + self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) + + def test_failed_transient_cleanup_preserves_disk_for_manual_recovery(self): + self.backend.fail_define = True + self.backend.fail_destroy = True + with self.assertRaises(self.error_type) as incomplete: + self.service.create_vm(self.spec()) + self.assertEqual(incomplete.exception.status, 502) + self.assertEqual(len(self.backend.domains), 1) + self.assertTrue(self.backend.domains[0].isActive()) + self.assertFalse(self.backend.domains[0].isPersistent()) + self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) + + def test_failed_volume_cleanup_reports_residual_disk(self): + self.backend.fail_create = True + self.backend.fail_volume_delete = True + with self.assertRaises(self.error_type) as incomplete: + self.service.create_vm(self.spec()) + self.assertEqual(incomplete.exception.status, 502) + self.assertFalse(self.backend.domains) + self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) + + def test_resources_refreshes_directory_pool_for_externally_added_iso(self): + iso_pool = self.backend.pools["iso"] + iso_pool.external_names.add("new-upload.iso") + self.assertNotIn("new-upload.iso", iso_pool.listVolumes()) + resources = self.service.resources() + self.assertIn("new-upload.iso", resources["isos"]) + self.assertEqual(iso_pool.refreshes, 1) + + def test_create_refreshes_directory_pool_for_externally_added_iso(self): + iso_pool = self.backend.pools["iso"] + iso_pool.external_names.add("new-upload.iso") + self.assertNotIn("new-upload.iso", iso_pool.listVolumes()) + vm = self.service.create_vm(self.spec(iso="new-upload.iso")) + self.assertEqual(vm["state"], "running") + cdrom = self.backend.domains[0].root.find( + "./devices/disk[@device='cdrom']/source") + self.assertEqual(cdrom.get("file"), + "/var/lib/libvirt/iso/new-upload.iso") + self.assertEqual(iso_pool.refreshes, 1) + + def test_existing_disk_name_is_never_overwritten(self): + pool = self.backend.pools["images"] + existing = FakeVolume(pool, "alma-test.qcow2") + pool.volumes[existing.name()] = existing + with self.assertRaises(self.error_type) as collision: + self.service.create_vm(self.spec()) + self.assertEqual(collision.exception.status, 409) + self.assertIs(pool.volumes[existing.name()], existing) + self.assertFalse(self.backend.domains) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_external_same_name_disk_is_detected_after_pool_refresh(self): + disk_pool = self.backend.pools["images"] + disk_pool.external_names.add("alma-test.qcow2") + self.assertNotIn("alma-test.qcow2", disk_pool.listVolumes()) + with self.assertRaises(self.error_type) as collision: + self.service.create_vm(self.spec()) + self.assertEqual(collision.exception.status, 409) + self.assertIn("alma-test.qcow2", disk_pool.volumes) + self.assertEqual(disk_pool.refreshes, 1) + self.assertFalse(self.backend.domains) + + def test_create_rejects_disk_larger_than_available_pool_space(self): + with self.assertRaises(self.error_type) as insufficient: + self.service.create_vm(self.spec(disk_gib=100)) + self.assertEqual(insufficient.exception.status, 409) + self.assertFalse(self.backend.pools["images"].volumes) + + def test_actions_and_safe_deletion(self): + vm = self.service.create_vm(self.spec()) + vm_uuid = vm["uuid"] + with self.assertRaises(self.error_type) as running: + self.service.delete_vm(vm_uuid, True) + self.assertEqual(running.exception.status, 409) + self.assertEqual(self.service.action(vm_uuid, "reset")["state"], "running") + self.assertEqual(self.backend.domains[0].last_reset_flags, 0) + self.assertEqual(self.service.action(vm_uuid, "reboot")["state"], "shutoff") + self.assertEqual(self.service.action(vm_uuid, "start")["state"], "running") + self.assertEqual(self.service.action(vm_uuid, "shutdown")["state"], "shutoff") + with self.assertRaises(self.error_type): + self.service.console_port(vm_uuid) + self.assertEqual(self.service.action(vm_uuid, "start")["state"], "running") + self.assertEqual(self.service.action(vm_uuid, "poweroff")["state"], "shutoff") + result = self.service.delete_vm(vm_uuid, True) + self.assertEqual(result["deleted_disks"], ["alma-test.qcow2"]) + self.assertFalse(self.backend.pools["images"].volumes) + self.assertFalse(self.backend.domains) + + def test_legacy_panel_uuid_disk_can_still_be_deleted(self): + vm = self.service.create_vm(self.spec()) + self.service.action(vm["uuid"], "shutdown") + old_name = f"panel-{vm['uuid']}.qcow2" + pool = self.backend.pools["images"] + del pool.volumes["alma-test.qcow2"] + pool.volumes[old_name] = FakeVolume(pool, old_name) + root = self.backend.domains[0].root + os_node = root.find("os") + os_node.attrib.pop("firmware", None) + nvram = os_node.find("nvram") + if nvram is not None: + os_node.remove(nvram) + marker = root.find("./metadata/{urn:virsh-panel:1}managed") + marker.attrib = {"version": "1"} + disk = root.find("./devices/disk[@device='disk']") + disk.set("type", "volume") + disk.find("source").attrib = {"pool": "images", "volume": old_name} + self.assertEqual(self.service.delete_vm(vm["uuid"], True)["deleted_disks"], + [old_name]) + self.assertNotIn(old_name, pool.volumes) + + def test_disk_deletion_rejects_other_domain_reference(self): + vm = self.service.create_vm(self.spec()) + self.service.action(vm["uuid"], "shutdown") + original = self.backend.domains[0] + other_xml = ET.fromstring(original.XMLDesc(0)) + other_xml.find("uuid").text = str(uuid.uuid4()) + other_xml.find("name").text = "other-vm" + self.backend.domains.append(FakeDomain(self.backend, ET.tostring(other_xml))) + with self.assertRaises(self.error_type) as shared: + self.service.delete_vm(vm["uuid"], True) + self.assertEqual(shared.exception.status, 409) + self.assertEqual(len(self.backend.domains), 2) + + def test_definition_only_delete_keeps_volume_and_nvram(self): + vm = self.service.create_vm(self.spec()) + self.service.action(vm["uuid"], "shutdown") + result = self.service.delete_vm(vm["uuid"], False) + self.assertEqual(result["deleted_disks"], []) + self.assertEqual(self.backend.undefine_flags, [8]) + self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) + self.assertFalse(self.backend.domains) + + def test_disk_deletion_rejects_backing_image_reference(self): + vm = self.service.create_vm(self.spec()) + self.service.action(vm["uuid"], "shutdown") + other_xml = ET.fromstring(self.backend.domains[0].XMLDesc(0)) + other_xml.find("uuid").text = str(uuid.uuid4()) + other_xml.find("name").text = "clone-vm" + disk = other_xml.find("./devices/disk[@device='disk']") + disk.set("type", "volume") + disk.find("source").attrib = {"pool": "images", "volume": "independent.qcow2"} + backing = ET.SubElement(disk, "backingStore", type="volume") + ET.SubElement(backing, "source", pool="images", + volume="alma-test.qcow2") + self.backend.domains.append(FakeDomain(self.backend, ET.tostring(other_xml))) + with self.assertRaises(self.error_type) as shared: + self.service.delete_vm(vm["uuid"], True) + self.assertEqual(shared.exception.status, 409) + + def test_disk_deletion_rejects_nested_data_store_reference(self): + vm = self.service.create_vm(self.spec()) + self.service.action(vm["uuid"], "shutdown") + other_xml = ET.fromstring(self.backend.domains[0].XMLDesc(0)) + other_xml.find("uuid").text = str(uuid.uuid4()) + other_xml.find("name").text = "data-store-vm" + source = other_xml.find("./devices/disk[@device='disk']/source") + source.attrib = {"file": "/var/lib/libvirt/images/independent.qcow2"} + data_store = ET.SubElement(source, "dataStore", type="file") + ET.SubElement(data_store, "source", + file="/var/lib/libvirt/images/alma-test.qcow2") + self.backend.domains.append(FakeDomain(self.backend, ET.tostring(other_xml))) + with self.assertRaises(self.error_type) as shared: + self.service.delete_vm(vm["uuid"], True) + self.assertEqual(shared.exception.status, 409) + self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) + self.assertEqual(len(self.backend.domains), 2) + + def test_disk_deletion_rejects_nested_mirror_reference(self): + vm = self.service.create_vm(self.spec()) + self.service.action(vm["uuid"], "shutdown") + other_xml = ET.fromstring(self.backend.domains[0].XMLDesc(0)) + other_xml.find("uuid").text = str(uuid.uuid4()) + other_xml.find("name").text = "mirror-vm" + source = other_xml.find("./devices/disk[@device='disk']/source") + source.attrib = {"file": "/var/lib/libvirt/images/independent.qcow2"} + mirror = ET.SubElement(other_xml.find("./devices/disk[@device='disk']"), + "mirror", type="file") + ET.SubElement(mirror, "source", + file="/var/lib/libvirt/images/alma-test.qcow2") + self.backend.domains.append(FakeDomain(self.backend, ET.tostring(other_xml))) + with self.assertRaises(self.error_type) as shared: + self.service.delete_vm(vm["uuid"], True) + self.assertEqual(shared.exception.status, 409) + self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) + self.assertEqual(len(self.backend.domains), 2) + + def test_cloud_vm_uses_panel_reserved_uuid_for_credential_binding(self): + service = self.cloud_service() + reserved_uuid = str(uuid.uuid4()) + created = self.create_cloud_vm(service, self.cloud_spec(vm_uuid=reserved_uuid)) + self.assertEqual(created["uuid"], reserved_uuid) + self.assertEqual(created["credential_generation"], + f"panel-seed-{reserved_uuid}.iso") + self.assertEqual(created["disks"][0]["capacity_gib"], 20) + + def test_cloud_vm_accepts_almalinux_9_panel_template_volume(self): + service = self.cloud_service() + alma9_volume = "panel-template-alma9-12345678-0123456789abcdef.qcow2" + self.backend.pools["images"].volumes[alma9_volume] = FakeVolume( + self.backend.pools["images"], alma9_volume, capacity=2 * 1024**3, + ) + with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED", + create=True): + created = service.create_cloud_vm( + self.cloud_spec(os_name="AlmaLinux 9"), alma9_volume, + ) + self.assertEqual(created["os_name"], "AlmaLinux 9") + self.assertEqual(self.backend.pools["images"].volumes["cloud-vm.qcow2"].cloned_from, + alma9_volume) + + def test_cloud_vm_clones_template_and_uses_nonboot_seed_iso(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec(os_name="AlmaLinux 10")) + + self.assertEqual(created["state"], "running") + self.assertEqual(created["name"], "cloud-vm") + self.assertTrue(created["autostart"]) + self.assertEqual(self.backend.domain_autostart_changed, [created["uuid"]]) + pool = self.backend.pools["images"] + self.assertIn(TEMPLATE_NAME, pool.volumes) + self.assertEqual(pool.volumes["cloud-vm.qcow2"].cloned_from, + TEMPLATE_NAME) + self.assertEqual(pool.volumes["cloud-vm.qcow2"].capacity, 20 * 1024**3) + root = self.backend.domains[0].root + self.assertEqual([node.get("dev") for node in root.findall("./os/boot")], + ["hd"]) + self.assertIsNone(root.find("on_reboot")) + self.assertEqual(root.find("./devices/interface").get("type"), "bridge") + self.assertEqual(root.find("./devices/interface/source").get("bridge"), "br0") + self.assertEqual(root.find("./devices/interface/driver").get("queues"), "4") + mac = root.find("./devices/interface/mac").get("address") + self.assertRegex(mac, r"^([0-9a-f]{2}:){5}[0-9a-f]{2}$") + self.assertEqual(root.find("./devices/interface")[0].tag, "mac") + + cdroms = root.findall("./devices/disk[@device='cdrom']") + self.assertEqual(len(cdroms), 1) + self.assertIsNotNone(cdroms[0].find("readonly")) + seed_path = cdroms[0].find("source").get("file") + self.assertTrue(seed_path.startswith("/var/lib/libvirt/images/")) + self.assertTrue(seed_path.endswith(".iso")) + seed_name = seed_path.rsplit("/", 1)[-1] + self.assertIn(seed_name, pool.volumes) + self.assertGreater(len(pool.volumes[seed_name].contents), 0) + self.assertTrue(self.backend.streams[-1].finished) + + managed = root.find("./metadata/{urn:virsh-panel:1}managed") + self.assertEqual(managed.get("disk-volume"), "cloud-vm.qcow2") + self.assertEqual(managed.get("seed-volume"), seed_name) + self.assertEqual(managed.get("public-ip-cidr"), "8.8.8.18/24") + self.assertEqual(created["public_ip_cidr"], "8.8.8.18/24") + self.assertEqual(managed.get("os-source"), "cloud_template") + self.assertEqual(managed.get("os-name"), "AlmaLinux 10") + self.assertEqual(managed.get("created-at"), created["created_at"]) + self.assertRegex(created["created_at"], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") + self.assertEqual(created["os_name"], "AlmaLinux 10") + self.assertEqual(created["os_source"], "cloud_template") + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_cloud_vm_delete_disks_removes_clone_and_seed_but_keeps_template(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + root = self.backend.domains[0].root + seed_name = root.find("./metadata/{urn:virsh-panel:1}managed").get("seed-volume") + service.action(created["uuid"], "shutdown") + + deleted = service.delete_vm(created["uuid"], True) + self.assertEqual(set(deleted["deleted_disks"]), {"cloud-vm.qcow2", seed_name}) + self.assertEqual(set(self.backend.pools["images"].volumes), + {TEMPLATE_NAME}) + + def test_cloud_vm_definition_only_delete_keeps_clone_seed_and_template(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + volumes_before = set(self.backend.pools["images"].volumes) + service.action(created["uuid"], "shutdown") + + deleted = service.delete_vm(created["uuid"], False) + self.assertEqual(deleted["deleted_disks"], []) + self.assertEqual(set(self.backend.pools["images"].volumes), volumes_before) + + def test_cloud_vm_seed_shared_with_other_vm_blocks_disk_deletion(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + service.action(created["uuid"], "shutdown") + original = self.backend.domains[0] + copied_xml = ET.fromstring(original.XMLDesc(0)) + copied_xml.find("uuid").text = str(uuid.uuid4()) + copied_xml.find("name").text = "other-vm" + copied_xml.find("./devices/disk[@device='disk']/source").set( + "file", "/var/lib/libvirt/images/independent.qcow2", + ) + self.backend.domains.append(FakeDomain(self.backend, ET.tostring(copied_xml))) + volumes_before = set(self.backend.pools["images"].volumes) + + with self.assertRaises(self.error_type) as shared: + service.delete_vm(created["uuid"], True) + self.assertEqual(shared.exception.status, 409) + self.assertEqual(set(self.backend.pools["images"].volumes), volumes_before) + self.assertEqual(len(self.backend.domains), 2) + + def test_cloud_vm_invalid_public_network_is_rejected_before_volume_creation(self): + service = self.cloud_service() + bad_specs = [ + self.cloud_spec(public_ip_cidr="192.168.1.18/24"), + self.cloud_spec(public_ip_cidr="8.8.8.18/28", gateway="8.8.8.1"), + self.cloud_spec(public_ip_cidr="8.8.8.0/24"), + self.cloud_spec(public_ip_cidr="8.8.8.255/24"), + self.cloud_spec(dns_servers=["not-an-ip"]), + self.cloud_spec(guest_ssh_public_key="not-a-key"), + ] + for spec in bad_specs: + with self.subTest(spec=spec), self.assertRaises(self.error_type): + self.create_cloud_vm(service, spec) + self.assertEqual(set(self.backend.pools["images"].volumes), + {TEMPLATE_NAME}) + self.assertFalse(self.backend.domains) + + def test_cloud_vm_rejects_duplicate_public_ip_on_same_host(self): + service = self.cloud_service() + first = self.create_cloud_vm(service, self.cloud_spec()) + self.assertEqual(first["state"], "running") + volumes_before = set(self.backend.pools["images"].volumes) + + with self.assertRaises(self.error_type) as duplicate: + self.create_cloud_vm(service, self.cloud_spec( + name="cloud-vm-two", public_ip_cidr="8.8.8.18/28", + gateway="8.8.8.17", + )) + self.assertEqual(duplicate.exception.status, 409) + self.assertEqual(set(self.backend.pools["images"].volumes), volumes_before) + self.assertEqual(len(self.backend.domains), 1) + + def test_cloud_vm_clone_failure_keeps_template_and_no_partial_vm(self): + service = self.cloud_service() + self.backend.fail_clone = True + with self.assertRaises(self.error_type): + self.create_cloud_vm(service, self.cloud_spec()) + self.assertEqual(set(self.backend.pools["images"].volumes), + {TEMPLATE_NAME}) + self.assertFalse(self.backend.domains) + + def test_cloud_vm_seed_upload_failure_cleans_only_new_volumes(self): + service = self.cloud_service() + self.backend.fail_send = True + with self.assertRaises(self.error_type): + self.create_cloud_vm(service, self.cloud_spec()) + self.assertEqual(set(self.backend.pools["images"].volumes), + {TEMPLATE_NAME}) + self.assertFalse(self.backend.domains) + self.assertTrue(self.backend.streams[-1].aborted) + + def test_cloud_vm_start_failure_undefines_domain_and_removes_new_volumes(self): + service = self.cloud_service() + self.backend.bridge_active = False + with self.assertRaises(self.error_type): + self.create_cloud_vm(service, self.cloud_spec()) + self.assertEqual(set(self.backend.pools["images"].volumes), + {TEMPLATE_NAME}) + self.assertFalse(self.backend.domains) + self.assertEqual(self.backend.undefine_flags, [4]) + + def test_cloud_vm_autostart_failure_rolls_back_new_vm_and_volumes(self): + service = self.cloud_service() + self.backend.fail_domain_autostart = True + with self.assertRaises(self.error_type) as failure: + self.create_cloud_vm(service, self.cloud_spec()) + self.assertEqual(failure.exception.status, 502) + self.assertIn("开机自启", str(failure.exception)) + self.assertEqual(set(self.backend.pools["images"].volumes), {TEMPLATE_NAME}) + self.assertFalse(self.backend.domains) + self.assertEqual(self.backend.domain_starts, 0) + self.assertEqual(self.backend.domain_autostart_changed, []) + + def test_reinstall_keeps_original_public_network_and_deletes_old_disk_only_after_start(self): + from virsh_panel.cloud_init import read_seed_network + + service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + old_disk = pool.volumes["cloud-vm.qcow2"] + original_mac = domain.root.find("./devices/interface/mac").get("address") + old_delete = old_disk.delete + + def delete_after_new_start(flags): + self.assertTrue(domain.isActive()) + source = domain.root.find("./devices/disk[@device='disk']/source") + self.assertNotEqual(source.get("file"), old_disk.path()) + return old_delete(flags) + + old_disk.delete = delete_after_new_start + result = service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + os_name="AlmaLinux 10.2", + ssh_public_key=spec["guest_ssh_public_key"], + ) + + self.assertEqual(result["vm"]["uuid"], created["uuid"]) + self.assertEqual(result["vm"]["state"], "running") + self.assertEqual(result["vm"]["public_ip_cidr"], spec["public_ip_cidr"]) + self.assertEqual(result["vm"]["os_name"], "AlmaLinux 10.2") + self.assertFalse(result.get("warning")) + self.assertEqual(self.backend.shutdown_calls, 1) + self.assertNotIn("cloud-vm.qcow2", pool.volumes) + self.assertNotIn(old_seed_name, pool.volumes) + self.assertIn(TEMPLATE_NAME, pool.volumes) + self.assertIn("cloud-vm.qcow2", self.backend.deleted_volumes) + self.assertIn(old_seed_name, self.backend.deleted_volumes) + root = domain.root + self.assertEqual(root.find("./devices/interface/mac").get("address"), original_mac) + new_seed_name = root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed").get("seed-volume") + self.assertNotEqual(new_seed_name, old_seed_name) + network = read_seed_network(bytes(pool.volumes[new_seed_name].contents)) + self.assertEqual(network, { + "public_ip_cidr": spec["public_ip_cidr"], + "gateway": spec["gateway"], + "dns_servers": spec["dns_servers"], + "mac": original_mac, + }) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_reinstall_waits_for_graceful_shutdown_and_times_out_without_touching_disks(self): + service, created, spec, domain, _seed_name = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + before = set(pool.volumes) + self.backend.shutdown_stalls = True + + with patch.object(self.service_module, "REINSTALL_SHUTDOWN_TIMEOUT", 0), \ + patch.object(self.service_module, "REINSTALL_SHUTDOWN_POLL_INTERVAL", 0): + with self.assertRaises(self.error_type) as raised: + service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + + self.assertEqual(raised.exception.status, 409) + self.assertTrue(domain.isActive()) + self.assertEqual(self.backend.shutdown_calls, 1) + self.assertEqual(set(pool.volumes), before) + self.assertEqual(self.backend.deleted_volumes, []) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_reinstall_define_failure_preserves_original_definition_and_volumes(self): + service, created, spec, domain, _seed_name = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + before = set(pool.volumes) + original_disk = domain.root.find("./devices/disk[@device='disk']/source").get("file") + self.backend.fail_define = True + + with self.assertRaises(self.error_type): + service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + + self.assertEqual(set(pool.volumes), before) + self.assertEqual(domain.root.find("./devices/disk[@device='disk']/source").get("file"), + original_disk) + self.assertIn("cloud-vm.qcow2", pool.volumes) + self.assertNotIn("cloud-vm.qcow2", self.backend.deleted_volumes) + + def test_reinstall_start_failure_rolls_back_definition_and_keeps_old_disk(self): + service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + before = set(pool.volumes) + original_disk = domain.root.find("./devices/disk[@device='disk']/source").get("file") + self.backend.fail_domain_create = True + + with self.assertRaises(self.error_type): + service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + + self.assertEqual(set(pool.volumes), before) + self.assertEqual(domain.root.find("./devices/disk[@device='disk']/source").get("file"), + original_disk) + self.assertIn("cloud-vm.qcow2", pool.volumes) + self.assertIn(old_seed_name, pool.volumes) + self.assertNotIn("cloud-vm.qcow2", self.backend.deleted_volumes) + + def test_reinstall_transport_error_after_start_preserves_both_disks(self): + service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + self.backend.fail_domain_create_after_start = True + + result = service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + + self.assertTrue(domain.isActive()) + self.assertIn("旧系统盘已保留", result["warning"]) + self.assertIn("cloud-vm.qcow2", pool.volumes) + self.assertIn(old_seed_name, pool.volumes) + self.assertNotIn("cloud-vm.qcow2", self.backend.deleted_volumes) + self.assertNotEqual( + domain.root.find("./devices/disk[@device='disk']/source").get("file"), + pool.volumes["cloud-vm.qcow2"].path(), + ) + + def test_reinstall_old_disk_delete_failure_reports_warning_and_keeps_new_vm(self): + service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + self.backend.fail_volume_delete = True + + result = service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + + self.assertEqual(result["vm"]["state"], "running") + self.assertTrue(result.get("warning")) + self.assertTrue(domain.isActive()) + self.assertIn("cloud-vm.qcow2", pool.volumes) + self.assertIn(old_seed_name, pool.volumes) + new_disk_name = domain.root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed").get("disk-volume") + self.assertNotEqual(new_disk_name, "cloud-vm.qcow2") + self.assertIn(new_disk_name, pool.volumes) + self.assertIn(TEMPLATE_NAME, pool.volumes) + + def test_reinstall_password_mode_writes_only_hash_to_new_seed(self): + from virsh_panel.cloud_init import hash_root_password + + service, created, _spec, domain, _seed_name = self.cloud_vm_with_real_seed() + password = "Another-strong-guest-password-2026" + password_hash = hash_root_password(password) + result = service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + root_password_hash=password_hash, + ) + + self.assertEqual(result["vm"]["state"], "running") + new_seed_name = domain.root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed").get("seed-volume") + seed = bytes(self.backend.pools["images"].volumes[new_seed_name].contents) + self.assertIn(password_hash.encode(), seed) + self.assertNotIn(password.encode(), seed) + + def test_cloud_vm_can_be_reinstalled_more_than_once(self): + service, created, spec, domain, original_seed = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + + service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + first_managed = domain.root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + first_disk = first_managed.get("disk-volume") + first_seed = first_managed.get("seed-volume") + self.assertNotEqual(first_seed, original_seed) + + second = service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + second_managed = domain.root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + second_disk = second_managed.get("disk-volume") + second_seed = second_managed.get("seed-volume") + + self.assertEqual(second["vm"]["state"], "running") + self.assertEqual(second["vm"]["created_at"], created["created_at"]) + self.assertNotEqual(first_disk, second_disk) + self.assertNotEqual(first_seed, second_seed) + self.assertNotIn(first_disk, pool.volumes) + self.assertNotIn(first_seed, pool.volumes) + self.assertEqual(set(pool.volumes), {TEMPLATE_NAME, second_disk, second_seed}) + self.assertEqual(self.backend.shutdown_calls, 2) + + def test_reinstall_refuses_iso_or_snapshotted_vm_without_shutdown(self): + service, created, spec, domain, _seed_name = self.cloud_vm_with_real_seed() + domain.snapshots = 1 + before = set(self.backend.pools["images"].volumes) + + with self.assertRaises(self.error_type) as raised: + service.reinstall_cloud_vm( + created["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + self.assertEqual(raised.exception.status, 409) + self.assertEqual(self.backend.shutdown_calls, 0) + self.assertEqual(set(self.backend.pools["images"].volumes), before) + + iso_vm = self.service.create_vm(self.spec(name="iso-vm")) + with self.assertRaises(self.error_type): + service.reinstall_cloud_vm( + iso_vm["uuid"], TEMPLATE_NAME, + ssh_public_key=spec["guest_ssh_public_key"], + ) + + def test_template_import_uploads_new_qcow2_volume_without_overwrite(self): + with tempfile.TemporaryDirectory() as directory: + image = pathlib.Path(directory) / "verified.qcow2" + payload = b"QFI\xfb" + b"verified cloud image fixture" + image.write_bytes(payload) + result = self.service.import_template(image, TEMPLATE_NAME, 2 * 1024**3) + + self.assertEqual(result["volume_name"], TEMPLATE_NAME) + self.assertEqual(result["image_bytes"], len(payload)) + self.assertEqual(bytes(self.backend.pools["images"].volumes[TEMPLATE_NAME].contents), + payload) + self.assertEqual(self.backend.pools["images"].volumes[TEMPLATE_NAME].capacity, + 2 * 1024**3) + self.assertTrue(self.backend.streams[-1].finished) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_template_import_stream_failure_deletes_only_new_volume(self): + with tempfile.TemporaryDirectory() as directory: + image = pathlib.Path(directory) / "verified.qcow2" + image.write_bytes(b"QFI\xfbverified cloud image fixture") + self.backend.fail_send = True + with self.assertRaises(self.error_type): + self.service.import_template(image, TEMPLATE_NAME, 2 * 1024**3) + + self.assertNotIn(TEMPLATE_NAME, self.backend.pools["images"].volumes) + self.assertTrue(self.backend.streams[-1].aborted) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_template_import_rejects_wrong_remote_capacity_and_cleans_volume(self): + with tempfile.TemporaryDirectory() as directory: + image = pathlib.Path(directory) / "verified.qcow2" + image.write_bytes(b"QFI\xfbverified cloud image fixture") + with patch.object(FakeVolume, "info", return_value=(0, 1024**3, 100, 0)): + with self.assertRaises(self.error_type) as raised: + self.service.import_template(image, TEMPLATE_NAME, 2 * 1024**3) + + self.assertEqual(raised.exception.status, 502) + self.assertNotIn(TEMPLATE_NAME, self.backend.pools["images"].volumes) + self.assertEqual(self.backend.opened, self.backend.closed) + + def rescue_pool(self): + pool = self.backend.pools.get("rescue") + if pool is None: + pool = FakePool(self.backend, "rescue", "/home/rescue") + self.backend.pools["rescue"] = pool + return pool + + def rescue_volume(self): + pool = self.rescue_pool() + pool.volumes[RESCUE_NAME] = FakeVolume(pool, RESCUE_NAME, + capacity=1024 * 1024, fmt="raw") + return pool.volumes[RESCUE_NAME] + + def test_rescue_directory_is_registered_as_a_separate_persistent_pool(self): + configured = self.service.ensure_storage_pools() + self.assertEqual(configured, { + "storage_pool": "images", "iso_pool": "iso", + "rescue_iso_pool": self.backend.defined[-1][0], + }) + self.assertEqual(self.backend.defined[-1][1], "/home/rescue") + self.assertTrue(self.backend.pools[configured["rescue_iso_pool"]].autostart()) + self.assertEqual(self.backend.existing_dirs.intersection({"/home/rescue"}), + {"/home/rescue"}) + + def test_rescue_iso_is_separate_from_install_iso_list_and_creation(self): + self.rescue_volume() + self.assertEqual(self.service.resources()["isos"], ["AlmaLinux-10.iso"]) + self.assertEqual(self.service.create_vm(self.spec())["state"], "running") + with self.assertRaises(self.error_type) as missing: + self.service.create_vm(self.spec(name="rescue-as-installer", + iso="another-rescue.iso")) + self.assertEqual(missing.exception.status, 404) + # Even if somebody places a panel-named rescue ISO into the ordinary + # pool by hand, it must not become a selectable installation source. + normal_pool = self.backend.pools["iso"] + normal_pool.volumes[RESCUE_NAME] = FakeVolume(normal_pool, RESCUE_NAME) + self.assertNotIn(RESCUE_NAME, self.service.resources()["isos"]) + with self.assertRaises(self.error_type) as blocked: + self.service.create_vm(self.spec(name="rescue-as-installer", + iso=RESCUE_NAME)) + self.assertEqual(blocked.exception.status, 409) + + def test_rescue_operations_never_fall_back_to_normal_iso_pool(self): + ordinary = self.backend.pools["iso"] + ordinary.volumes[RESCUE_NAME] = FakeVolume(ordinary, RESCUE_NAME, + capacity=1024 * 1024, fmt="raw") + unconfigured = self.service.__class__( + self.service.uri, "images", "iso", "default") + with self.assertRaises(self.error_type) as missing: + unconfigured.delete_rescue_iso(RESCUE_NAME) + self.assertEqual(missing.exception.status, 409) + self.assertIn("配置救援 ISO", str(missing.exception)) + with tempfile.TemporaryDirectory() as directory: + image = pathlib.Path(directory) / "rescue.iso" + payload = bytearray(1024 * 1024) + payload[32769:32774] = b"CD001" + image.write_bytes(payload) + with self.assertRaises(self.error_type) as missing_upload: + unconfigured.import_rescue_iso(image, RESCUE_NAME) + self.assertEqual(missing_upload.exception.status, 409) + self.assertIn(RESCUE_NAME, ordinary.volumes) + + def test_rescue_pool_alias_of_install_iso_pool_is_rejected(self): + normal_pool = self.backend.pools["iso"] + alias = FakePool(self.backend, "rescue-alias", normal_pool.path) + self.backend.pools["rescue-alias"] = alias + service = self.service.__class__( + self.service.uri, "images", "iso", "default", + rescue_iso_pool="rescue-alias") + with self.assertRaises(self.error_type) as invalid: + service.ensure_storage_pools() + self.assertEqual(invalid.exception.status, 409) + with self.assertRaises(self.error_type) as invalid_lookup: + service.delete_rescue_iso(RESCUE_NAME) + self.assertEqual(invalid_lookup.exception.status, 409) + self.assertFalse(alias.volumes) + + def test_rescue_pool_alias_with_mixed_file_pool_types_is_rejected(self): + normal_pool = self.backend.pools["iso"] + alias = FakePool(self.backend, "rescue-fs-alias", normal_pool.path, + pool_type="fs") + self.backend.pools["rescue-fs-alias"] = alias + service = self.service.__class__( + self.service.uri, "images", "iso", "default", + rescue_iso_pool="rescue-fs-alias") + with self.assertRaises(self.error_type) as invalid: + service.ensure_storage_pools() + self.assertEqual(invalid.exception.status, 409) + with self.assertRaises(self.error_type) as invalid_lookup: + service.delete_rescue_iso(RESCUE_NAME) + self.assertEqual(invalid_lookup.exception.status, 409) + + def test_rescue_iso_import_rejects_invalid_file_and_never_overwrites(self): + self.rescue_pool() + with tempfile.TemporaryDirectory() as directory: + image = pathlib.Path(directory) / "rescue.iso" + image.write_bytes(b"not an ISO" * 10000) + with self.assertRaises(self.error_type) as invalid: + self.service.import_rescue_iso(image, RESCUE_NAME) + self.assertEqual(invalid.exception.status, 422) + self.assertNotIn(RESCUE_NAME, self.backend.pools["rescue"].volumes) + + payload = bytearray(1024 * 1024) + payload[32769:32774] = b"CD001" + image.write_bytes(payload) + imported = self.service.import_rescue_iso(image, RESCUE_NAME) + self.assertEqual(imported, {"volume_name": RESCUE_NAME, + "image_bytes": len(payload)}) + self.assertEqual(bytes(self.backend.pools["rescue"].volumes[RESCUE_NAME].contents), + payload) + with self.assertRaises(self.error_type) as exists: + self.service.import_rescue_iso(image, RESCUE_NAME) + self.assertEqual(exists.exception.status, 409) + + def test_rescue_iso_import_stream_failure_removes_only_new_volume(self): + self.rescue_pool() + with tempfile.TemporaryDirectory() as directory: + image = pathlib.Path(directory) / "rescue.iso" + payload = bytearray(1024 * 1024) + payload[32769:32774] = b"CD001" + image.write_bytes(payload) + self.backend.fail_send = True + with self.assertRaises(self.error_type): + self.service.import_rescue_iso(image, RESCUE_NAME) + self.assertNotIn(RESCUE_NAME, self.backend.pools["rescue"].volumes) + self.assertTrue(self.backend.streams[-1].aborted) + + def test_rescue_iso_delete_can_clean_corrupt_unreferenced_managed_volume(self): + pool = self.rescue_pool() + pool.volumes[RESCUE_NAME] = FakeVolume(pool, RESCUE_NAME, + capacity=1024, fmt="qcow2") + self.assertTrue(self.service.delete_rescue_iso(RESCUE_NAME)["deleted"]) + self.assertNotIn(RESCUE_NAME, pool.volumes) + + def test_rescue_boot_preserves_seed_cdrom_and_exit_restores_original_xml(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + original_disk_names = set(self.backend.pools["images"].volumes) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + + entered = service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertTrue(entered["vm"]["rescue_mode"]) + self.assertFalse(entered["vm"]["rescue_staged"]) + self.assertEqual(entered["vm"]["rescue_volume_name"], RESCUE_NAME) + self.assertTrue(self.backend.domains[0].autostart()) + rescue_root = self.backend.domains[0].root + self.assertEqual(len(rescue_root.findall("./devices/disk[@device='cdrom']")), 2) + self.assertIsNone(rescue_root.find("./os/boot")) + seed = rescue_root.findall("./devices/disk[@device='cdrom']")[0] + rescue = rescue_root.findall("./devices/disk[@device='cdrom']")[1] + self.assertIn("panel-seed-", seed.find("source").get("file")) + self.assertEqual(rescue.find("source").get("file"), + self.backend.pools["rescue"].volumes[RESCUE_NAME].path()) + self.assertEqual(rescue.find("boot").get("order"), "1") + self.assertEqual(rescue_root.find("./devices/disk[@device='disk']/boot").get("order"), + "2") + with self.assertRaises(self.error_type) as in_use: + service.delete_rescue_iso(RESCUE_NAME) + self.assertEqual(in_use.exception.status, 409) + + exited = service.exit_rescue_vm(created["uuid"], original_xml) + self.assertFalse(exited["vm"]["rescue_mode"]) + self.assertTrue(self.backend.domains[0].autostart()) + self.assertEqual(len(self.backend.domains[0].root.findall( + "./devices/disk[@device='cdrom']")), 1) + self.assertEqual(set(self.backend.pools["images"].volumes), original_disk_names) + self.assertEqual(self.backend.shutdown_calls, 2) + self.assertEqual(self.backend.destroyed, []) + self.assertTrue(service.delete_rescue_iso(RESCUE_NAME)["deleted"]) + + def test_stopped_vm_can_start_directly_in_rescue_mode(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + domain = self.backend.domains[0] + domain.shutdown() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + before = self.backend.shutdown_calls + result = service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertTrue(result["vm"]["rescue_mode"]) + self.assertEqual(self.backend.shutdown_calls, before) + self.assertEqual(self.backend.destroyed, []) + + def test_rescue_entry_rejects_changed_xml_before_shutdown(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + changed = ET.fromstring(original_xml) + changed.find("./memory").text = "8192" + self.backend.domains[0].define(ET.tostring(changed, encoding="unicode")) + with self.assertRaises(self.error_type) as mismatch: + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertEqual(mismatch.exception.status, 409) + self.assertEqual(self.backend.shutdown_calls, 0) + + def test_rescue_rejects_ambiguous_multi_disk_boot_before_shutdown(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + domain = self.backend.domains[0] + original = ET.fromstring(domain.XMLDesc(1)) + disk = original.find("./devices/disk[@device='disk']") + disk.find("target").set("dev", "vdb") + extra = copy.deepcopy(disk) + extra.find("target").set("dev", "vdc") + original.find("devices").append(extra) + domain.define(ET.tostring(original, encoding="unicode")) + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + with self.assertRaises(self.error_type) as ambiguous: + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertEqual(ambiguous.exception.status, 409) + self.assertEqual(self.backend.shutdown_calls, 0) + + def test_rescue_honors_explicit_boot_disk_in_multi_disk_vm(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + domain = self.backend.domains[0] + original = ET.fromstring(domain.XMLDesc(1)) + os_node = original.find("os") + for boot in list(os_node.findall("boot")): + os_node.remove(boot) + disk = original.find("./devices/disk[@device='disk']") + ET.SubElement(disk, "boot", order="2") + extra = copy.deepcopy(disk) + extra.find("target").set("dev", "vdb") + extra.find("boot").set("order", "1") + original.find("devices").append(extra) + domain.define(ET.tostring(original, encoding="unicode")) + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + booted_disks = [node.find("target").get("dev") for node in + domain.root.findall("./devices/disk[@device='disk']") + if node.find("boot") is not None] + self.assertEqual(booted_disks, ["vdb"]) + + def test_rescue_shutdown_timeout_never_forces_poweroff(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + self.backend.shutdown_stalls = True + with patch.object(self.service_module, "REINSTALL_SHUTDOWN_TIMEOUT", 0): + result = service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertTrue(result["pending_manual_restart"]) + self.assertIn("正常关机超时", result["warning"]) + self.assertIn("强制重启进入救援", result["warning"]) + self.assertIn("强制断电", result["warning"]) + self.assertIn("强制重置", result["warning"]) + self.assertNotIn("联系客服", result["warning"]) + self.assertTrue(self.backend.domains[0].running) + self.assertEqual(self.backend.destroyed, []) + domain = self.backend.domains[0] + self.assertFalse(result["vm"]["rescue_mode"]) + self.assertTrue(result["vm"]["rescue_staged"]) + self.assertEqual(result["vm"]["rescue_volume_name"], RESCUE_NAME) + self.assertIsNone(domain.root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}rescue")) + self.assertIsNotNone(domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}rescue")) + + # A QEMU reset uses its live configuration; a cold power cycle reads + # the durable rescue definition saved before the failed shutdown. + service.action(created["uuid"], "reset") + self.assertTrue(service.get_vm(created["uuid"])["rescue_staged"]) + before_starts = self.backend.domain_starts + forced = service.force_start_staged_rescue_vm(created["uuid"], original_xml) + self.assertEqual(self.backend.destroy_calls, 1) + self.assertEqual(self.backend.domain_starts, before_starts + 1) + self.assertTrue(forced["vm"]["rescue_mode"]) + self.assertTrue(service.get_vm(created["uuid"])["rescue_mode"]) + self.assertFalse(service.get_vm(created["uuid"])["rescue_staged"]) + self.backend.shutdown_stalls = False + service.exit_rescue_vm(created["uuid"], original_xml) + self.assertFalse(service.get_vm(created["uuid"])["rescue_mode"]) + + def test_rescue_shutdown_request_failure_instructs_manual_poweroff(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + domain = self.backend.domains[0] + with patch.object(domain, "shutdown", side_effect=FakeLibvirtError("ACPI unavailable")): + result = service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertTrue(result["pending_manual_restart"]) + self.assertIn("无法请求虚拟机正常关机", result["warning"]) + self.assertIn("强制重启进入救援", result["warning"]) + self.assertNotIn("联系客服", result["warning"]) + self.assertTrue(domain.running) + self.assertEqual(self.backend.destroyed, []) + self.assertFalse(service.get_vm(created["uuid"])["rescue_mode"]) + self.assertTrue(service.get_vm(created["uuid"])["rescue_staged"]) + + def test_rescue_shutdown_error_after_external_cold_start_reports_active(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + domain = self.backend.domains[0] + + def cold_start_then_error(): + domain.running = False + domain.live_root = None + domain.create() + raise FakeLibvirtError("shutdown result lost") + + with patch.object(domain, "shutdown", side_effect=cold_start_then_error): + result = service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertNotIn("pending_manual_restart", result) + self.assertTrue(result["vm"]["rescue_mode"]) + self.assertFalse(result["vm"]["rescue_staged"]) + self.assertIn("VNC", result["warning"]) + + def test_rescue_staged_exit_cancels_boot_without_stopping_running_vm(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + domain = self.backend.domains[0] + self.backend.shutdown_stalls = True + with patch.object(self.service_module, "REINSTALL_SHUTDOWN_TIMEOUT", 0): + result = service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertTrue(result["pending_manual_restart"]) + before_shutdowns = self.backend.shutdown_calls + before_starts = self.backend.domain_starts + exited = service.exit_rescue_vm(created["uuid"], original_xml) + self.assertFalse(exited["vm"]["rescue_mode"]) + self.assertFalse(exited["vm"]["rescue_staged"]) + self.assertTrue(domain.running) + self.assertEqual(self.backend.shutdown_calls, before_shutdowns) + self.assertEqual(self.backend.domain_starts, before_starts) + self.assertTrue(service.delete_rescue_iso(RESCUE_NAME)["deleted"]) + + def test_force_staged_rescue_rejects_wrong_backup_without_poweroff(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + self.backend.shutdown_stalls = True + with patch.object(self.service_module, "REINSTALL_SHUTDOWN_TIMEOUT", 0): + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + tampered = original_xml.replace("cloud-vm", "other-vm") + with self.assertRaises(self.error_type) as error: + service.force_start_staged_rescue_vm(created["uuid"], tampered) + self.assertEqual(error.exception.status, 409) + self.assertEqual(self.backend.destroy_calls, 0) + self.assertTrue(self.backend.domains[0].running) + + def test_force_staged_rescue_start_failure_keeps_iso_for_retry(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + self.backend.shutdown_stalls = True + with patch.object(self.service_module, "REINSTALL_SHUTDOWN_TIMEOUT", 0): + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.backend.fail_domain_create = True + with self.assertRaises(self.error_type) as error: + service.force_start_staged_rescue_vm(created["uuid"], original_xml) + self.assertEqual(error.exception.status, 502) + self.assertEqual(self.backend.destroy_calls, 1) + self.assertFalse(self.backend.domains[0].running) + self.assertTrue(service.get_vm(created["uuid"])["rescue_staged"]) + self.backend.fail_domain_create = False + retried = service.force_start_staged_rescue_vm(created["uuid"], original_xml) + self.assertTrue(retried["vm"]["rescue_mode"]) + self.assertFalse(retried["vm"]["rescue_staged"]) + self.assertEqual(self.backend.destroy_calls, 1) + + def test_force_staged_rescue_poweroff_failure_keeps_original_running(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + self.backend.shutdown_stalls = True + with patch.object(self.service_module, "REINSTALL_SHUTDOWN_TIMEOUT", 0): + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + before_starts = self.backend.domain_starts + self.backend.fail_destroy = True + with self.assertRaises(self.error_type) as error: + service.force_start_staged_rescue_vm(created["uuid"], original_xml) + self.assertEqual(error.exception.status, 502) + self.assertEqual(self.backend.domain_starts, before_starts) + self.assertTrue(self.backend.domains[0].running) + self.assertTrue(service.get_vm(created["uuid"])["rescue_staged"]) + + def test_rescue_staged_exit_after_manual_poweroff_starts_original_system(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + self.backend.shutdown_stalls = True + with patch.object(self.service_module, "REINSTALL_SHUTDOWN_TIMEOUT", 0): + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + service.action(created["uuid"], "poweroff") + self.assertTrue(service.get_vm(created["uuid"])["rescue_staged"]) + exited = service.exit_rescue_vm(created["uuid"], original_xml) + self.assertEqual(exited["vm"]["state"], "running") + self.assertFalse(exited["vm"]["rescue_mode"]) + self.assertFalse(exited["vm"]["rescue_staged"]) + + def test_rescue_start_failure_restores_original_vm(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + self.backend.fail_define = True + with self.assertRaises(self.error_type) as failure: + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertEqual(failure.exception.status, 502) + self.assertTrue(self.backend.domains[0].running) + self.assertFalse(service.get_vm(created["uuid"])["rescue_mode"]) + self.assertEqual(self.backend.destroyed, []) + + def test_rescue_guest_start_failure_restores_original_vm(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + original_create = FakeDomain.create + namespace = self.service_module.PANEL_NS + + def fail_rescue_start(self): + if self.inactive_root.find( + f"./metadata/{{{namespace}}}rescue") is not None: + raise FakeLibvirtError("rescue start failed") + return original_create(self) + + with patch.object(FakeDomain, "create", fail_rescue_start): + with self.assertRaises(self.error_type) as failure: + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertEqual(failure.exception.status, 502) + self.assertTrue(self.backend.domains[0].running) + self.assertFalse(service.get_vm(created["uuid"])["rescue_mode"]) + + def test_rescue_start_transport_error_after_boot_keeps_rescue_config(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + self.backend.fail_domain_create_after_start = True + result = service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertIn("warning", result) + self.assertTrue(result["vm"]["rescue_mode"]) + self.assertTrue(self.backend.domains[0].running) + + def test_rescue_exit_rejects_wrong_backup_without_shutdown(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + tampered = original_xml.replace("cloud-vm", "other-vm") + before = self.backend.shutdown_calls + with self.assertRaises(self.error_type) as failure: + service.exit_rescue_vm(created["uuid"], tampered) + self.assertEqual(failure.exception.status, 409) + self.assertEqual(self.backend.shutdown_calls, before) + + def test_rescue_exit_start_failure_restores_rescue_vm(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + original_create = FakeDomain.create + namespace = self.service_module.PANEL_NS + + def fail_normal_start(self): + if self.inactive_root.find(f"./metadata/{{{namespace}}}rescue") is None: + raise FakeLibvirtError("normal system start failed") + return original_create(self) + + with patch.object(FakeDomain, "create", fail_normal_start): + with self.assertRaises(self.error_type) as failure: + service.exit_rescue_vm(created["uuid"], original_xml) + self.assertEqual(failure.exception.status, 502) + self.assertTrue(self.backend.domains[0].running) + self.assertTrue(service.get_vm(created["uuid"])["rescue_mode"]) + self.assertEqual(self.backend.destroyed, []) + + def test_rescue_redefinition_restores_original_autostart_setting(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + self.rescue_volume() + domain = self.backend.domains[0] + domain.setAutostart(0) + original_xml = service.prepare_rescue_vm(created["uuid"], RESCUE_NAME) + original_define = FakeDomain.define + + def resetting_define(self, xml): + original_define(self, xml) + self.auto_start = True + + with patch.object(FakeDomain, "define", resetting_define): + service.enter_rescue_vm(created["uuid"], RESCUE_NAME, original_xml) + self.assertFalse(domain.autostart()) + service.exit_rescue_vm(created["uuid"], original_xml) + self.assertFalse(domain.autostart()) + + def test_metric_counters_use_bulk_libvirt_stats_for_running_domains(self): + constants = { + "VIR_DOMAIN_STATS_CPU_TOTAL": 2, + "VIR_DOMAIN_STATS_BALLOON": 4, + "VIR_DOMAIN_STATS_BLOCK": 8, + "VIR_DOMAIN_STATS_INTERFACE": 16, + "VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING": 32, + } + for name, value in constants.items(): + setattr(self.service_module.libvirt, name, value) + domain = types.SimpleNamespace( + UUIDString=lambda: "00000000-0000-4000-8000-000000000001", + info=lambda: (1, 2048 * 1024, 2048 * 1024, 2, 0), + ID=lambda: 7, + ) + calls = [] + + def get_stats(_connection, groups, flags): + calls.append((groups, flags)) + return [(domain, {"cpu.time": 123, "net.0.rx.bytes": 456})] + + with patch.object(FakeConnection, "getAllDomainStats", get_stats, create=True): + result = self.service.metric_counters() + self.assertEqual(calls, [(2 | 4 | 8 | 16, 32)]) + self.assertEqual(len(result), 1) + self.assertEqual(result[0].generation, 7) + self.assertEqual(result[0].vcpus, 2) + self.assertEqual(result[0].values["net.0.rx.bytes"], 456) + self.assertEqual(self.backend.opened, self.backend.closed) + + def test_metric_counters_skip_vm_disappearing_after_bulk_read(self): + constants = { + "VIR_DOMAIN_STATS_CPU_TOTAL": 2, + "VIR_DOMAIN_STATS_BALLOON": 4, + "VIR_DOMAIN_STATS_BLOCK": 8, + "VIR_DOMAIN_STATS_INTERFACE": 16, + "VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING": 32, + } + for name, value in constants.items(): + setattr(self.service_module.libvirt, name, value) + + def gone(): + raise FakeLibvirtError("domain vanished") + + disappearing = types.SimpleNamespace(info=gone) + healthy = types.SimpleNamespace( + UUIDString=lambda: "00000000-0000-4000-8000-000000000002", + info=lambda: (1, 2048 * 1024, 2048 * 1024, 2, 0), + ID=lambda: 8, + ) + with patch.object( + FakeConnection, "getAllDomainStats", + lambda _connection, _groups, _flags: [ + (disappearing, {"cpu.time": 1}), + (healthy, {"cpu.time": 2}), + ], create=True, + ): + result = self.service.metric_counters() + self.assertEqual(len(result), 1) + self.assertEqual(result[0].vm_id, "00000000-0000-4000-8000-000000000002") + self.assertEqual(self.backend.opened, self.backend.closed) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/tests/test_metrics.py b/engine/tests/test_metrics.py new file mode 100644 index 00000000..26ed456d --- /dev/null +++ b/engine/tests/test_metrics.py @@ -0,0 +1,470 @@ +"""VM metric math, DB persistence, and the process-local collection lifecycle.""" + +from __future__ import annotations + +import threading + +import pytest + +from virsh_panel.database import DatabaseStore +from virsh_panel.metrics import ( + MAX_QUERY_POINTS, RANGES, MetricSampler, MetricsCollector, RawVMStats, + host_scope, query_interval_seconds, +) + + +VM_ID = "00000000-0000-4000-8000-000000000001" +HOST = {"host": "hypervisor.example", "port": 2222, + "fingerprint": "SHA256:one", "storage_pool": "/home/kvm"} + + +def raw(*, generation=12, cpu=1_000_000_000, block_read=100, + block_write=200, network_rx=1000, network_tx=2000, + memory_time=1000, extra=None): + values = { + "cpu.time": cpu, + "balloon.available": 2 * 1024 * 1024, + "balloon.usable": 512 * 1024, + "balloon.last-update": memory_time, + "block.count": 1, + "block.0.name": "vda", + "block.0.rd.bytes": block_read, + "block.0.wr.bytes": block_write, + "net.count": 1, + "net.0.name": "vnet1", + "net.0.rx.bytes": network_rx, + "net.0.tx.bytes": network_tx, + } + values.update(extra or {}) + return RawVMStats(VM_ID, generation, 2, values) + + +def test_host_scope_ignores_pool_but_changes_with_ssh_host_identity(): + first = host_scope(HOST) + assert first == host_scope({**HOST, "storage_pool": "/different"}) + assert first != host_scope({**HOST, "fingerprint": "SHA256:two"}) + assert first != host_scope({**HOST, "port": 22}) + + +def test_interval_caps_all_ranges_at_600_epoch_aligned_buckets(): + for seconds in RANGES.values(): + interval = query_interval_seconds(seconds) + assert interval % 60 == 0 + assert seconds // interval + 2 <= MAX_QUERY_POINTS + + +def test_initial_sample_and_fresh_guest_memory_then_rates(): + sampler = MetricSampler() + scope = host_scope(HOST) + first = sampler.observe(scope, raw(), timestamp=1000, monotonic=10) + assert first["cpu_percent"] is None + assert first["disk_read_bps"] is None + assert first["network_rx_bps"] is None + assert first["memory_used_mib"] == 1536 + assert first["memory_total_mib"] == 2048 + + second = sampler.observe( + scope, + raw(cpu=61_000_000_000, block_read=700, block_write=1400, + network_rx=2200, network_tx=2600, memory_time=1050), + timestamp=1060, monotonic=70, + ) + assert second["cpu_percent"] == 50 + assert second["disk_read_bps"] == 10 + assert second["disk_write_bps"] == 20 + assert second["network_rx_bps"] == 20 + assert second["network_tx_bps"] == 10 + + +def test_cpu_time_over_vcpu_capacity_is_displayed_as_100_percent(): + sampler = MetricSampler() + scope = host_scope(HOST) + sampler.observe(scope, raw(), timestamp=1000, monotonic=10) + # 130 CPU-seconds across two vCPUs in a 60-second interval; libvirt can + # include QEMU auxiliary threads in cpu.time. + point = sampler.observe(scope, raw(cpu=131_000_000_000), + timestamp=1060, monotonic=70) + assert point["cpu_percent"] == 100 + + +def test_memory_missing_or_stale_balloon_stats_never_uses_rss_or_current(): + sampler = MetricSampler() + scope = host_scope(HOST) + values = {"balloon.current": 2 * 1024 * 1024, "balloon.rss": 512 * 1024} + for extra in ( + {"balloon.last-update": 1}, + {"balloon.usable": None}, + {"balloon.available": None}, + ): + point = sampler.observe(scope, raw(extra={**values, **extra}), + timestamp=1000, monotonic=10) + assert point["memory_used_mib"] is None + assert point["memory_total_mib"] is None + + +def test_counter_reset_reboot_device_change_and_partial_data_are_unknown(): + sampler = MetricSampler() + scope = host_scope(HOST) + sampler.observe(scope, raw(), timestamp=1000, monotonic=10) + reset = sampler.observe(scope, raw(cpu=100, block_read=1, network_rx=1), + timestamp=1060, monotonic=70) + assert reset["cpu_percent"] is None + assert reset["disk_read_bps"] is None + assert reset["network_rx_bps"] is None + + # Even if a second disk masks the first disk's decreasing counter in the + # aggregate, device change must not produce a transient spike. + changed = sampler.observe(scope, raw(extra={ + "block.count": 2, "block.1.name": "vdb", + "block.1.rd.bytes": 10_000, "block.1.wr.bytes": 20_000, + }), timestamp=1120, monotonic=130) + assert changed["disk_read_bps"] is None + assert changed["disk_write_bps"] is None + + partial = sampler.observe(scope, raw(extra={ + "block.count": 2, "block.1.name": "vdb", + "block.1.rd.bytes": 11_000, + }), timestamp=1180, monotonic=190) + assert partial["disk_write_bps"] is None # second device missing wr.bytes + assert partial["disk_read_bps"] is not None + + reboot = sampler.observe(scope, raw(generation=13, cpu=200_000_000_000), + timestamp=1240, monotonic=250) + assert reboot["cpu_percent"] is None + assert reboot["network_tx_bps"] is None + + +def test_cdrom_without_byte_counters_does_not_hide_disk_rates(): + sampler = MetricSampler() + scope = host_scope(HOST) + cdrom = {"block.count": 2, "block.1.name": "sda"} + sampler.observe(scope, raw(extra=cdrom), timestamp=1000, monotonic=10) + second = sampler.observe( + scope, raw(block_read=700, block_write=1400, extra={ + **cdrom, "balloon.last-update": 1060, + }), timestamp=1060, monotonic=70, + ) + assert second["disk_read_bps"] == 10 + assert second["disk_write_bps"] == 20 + + +def test_single_device_counter_rollback_is_not_masked_by_another_device(): + sampler = MetricSampler() + scope = host_scope(HOST) + second_disk = {"block.count": 2, "block.1.name": "vdb", + "block.1.rd.bytes": 1_000, "block.1.wr.bytes": 1_000} + sampler.observe(scope, raw(extra=second_disk), timestamp=1000, monotonic=10) + point = sampler.observe(scope, raw(block_read=1, block_write=1, extra={ + **second_disk, "block.1.rd.bytes": 10_000, + "block.1.wr.bytes": 10_000, + }), timestamp=1060, monotonic=70) + assert point["disk_read_bps"] is None + assert point["disk_write_bps"] is None + + +def test_unobserved_long_gap_is_not_averaged_as_current_rate(): + sampler = MetricSampler() + scope = host_scope(HOST) + sampler.observe(scope, raw(), timestamp=1000, monotonic=10) + delayed = sampler.observe(scope, raw(cpu=50_000_000_000, block_read=2000), + timestamp=1600, monotonic=610) + assert delayed["cpu_percent"] is None + assert delayed["disk_read_bps"] is None + + +class FakeCursor: + def __init__(self, rows=(), delete_counts=()): + self.rows = rows + self.commands = [] + self.delete_counts = list(delete_counts) + self.rowcount = 0 + + def __enter__(self): + return self + + def __exit__(self, *_args): + return None + + def execute(self, sql, args=None): + self.commands.append((sql, args)) + self.rowcount = (self.delete_counts.pop(0) + if sql.startswith("DELETE FROM vm_metric_samples") + and self.delete_counts else 0) + + def executemany(self, sql, args): + self.commands.append((sql, args)) + + def fetchall(self): + return self.rows + + +class FakeConnection: + def __init__(self, rows=(), delete_counts=()): + self.fake_cursor = FakeCursor(rows, delete_counts) + self.commits = 0 + self.closed = False + + def cursor(self): + return self.fake_cursor + + def commit(self): + self.commits += 1 + + def rollback(self): + raise AssertionError("unexpected rollback") + + def close(self): + self.closed = True + + +def test_metric_and_user_tables_created_with_record_table(): + connection = FakeConnection() + store = DatabaseStore.__new__(DatabaseStore) + store._connect = lambda: connection + store._initialize_schema() + assert len(connection.fake_cursor.commands) == 6 + assert "vm_metric_samples" in connection.fake_cursor.commands[1][0] + assert "vm_metric_retention" in connection.fake_cursor.commands[1][0] + assert "CREATE TABLE IF NOT EXISTS users" in connection.fake_cursor.commands[2][0] + assert "CREATE TABLE IF NOT EXISTS registration_codes" in connection.fake_cursor.commands[3][0] + assert "CREATE TABLE IF NOT EXISTS vm_ownership" in connection.fake_cursor.commands[4][0] + assert "CREATE TABLE IF NOT EXISTS user_ssh_keys" in connection.fake_cursor.commands[5][0] + assert connection.commits == 1 and connection.closed + + +def test_metric_store_prunes_physically_and_queries_only_scoped_recent_data(): + scope = host_scope(HOST) + connection = FakeConnection([{ + "timestamp": 1000, + "cpu_percent": 12.5, + "memory_used_mib": 1024, + "memory_total_mib": 2048, + "disk_read_bps": None, + "disk_write_bps": None, + "network_rx_bps": 256, + "network_tx_bps": 0, + }]) + store = DatabaseStore.__new__(DatabaseStore) + store._connect = lambda: connection + point = {"vm_id": VM_ID, "timestamp": 1000, "cpu_percent": 12.5, + "memory_used_mib": 1024, "memory_total_mib": 2048, + "disk_read_bps": None, "disk_write_bps": None, + "network_rx_bps": 256, "network_tx_bps": 0} + store.save_metric_samples(scope, [point]) + store.prune_metric_samples(500) + result = store.query_metric_samples(scope, VM_ID, since=500, until=1100, + interval_seconds=60, limit=600) + assert result[0]["cpu_percent"] == 12.5 + assert result[0]["disk_read_bps"] is None + insert, delete, query = connection.fake_cursor.commands + assert "INSERT INTO vm_metric_samples" in insert[0] + assert "DELETE FROM vm_metric_samples WHERE sampled_at < %s" in delete[0] + assert delete[1] == (500, 5000) + assert "host_scope=%s AND vm_uuid=%s AND sampled_at >= %s" in query[0] + assert "LIMIT %s" in query[0] + assert query[1] == (scope, VM_ID, 500, 1100, 60, 600) + assert connection.commits == 2 and connection.closed + + +def test_metric_prune_is_one_index_ordered_batch_per_transaction(): + connection = FakeConnection(delete_counts=[5000] * 10) + store = DatabaseStore.__new__(DatabaseStore) + store._connect = lambda: connection + assert store.prune_metric_samples(1234) == 5000 + assert len(connection.fake_cursor.commands) == 1 + assert connection.commits == 1 and connection.closed + assert all("ORDER BY sampled_at LIMIT %s" in command + and args == (1234, 5000) + for command, args in connection.fake_cursor.commands) + + +def test_metric_prune_reports_short_final_batch(): + connection = FakeConnection(delete_counts=[275]) + store = DatabaseStore.__new__(DatabaseStore) + store._connect = lambda: connection + assert store.prune_metric_samples(1234) == 275 + assert len(connection.fake_cursor.commands) == 1 + assert connection.commits == 1 + + +def test_metric_store_rejects_invalid_host_and_uuid_before_db_query(): + store = DatabaseStore.__new__(DatabaseStore) + store._connect = lambda: pytest.fail("invalid scope must not query database") + with pytest.raises(ValueError): + store.query_metric_samples("bad-scope", VM_ID, since=0, until=1, + interval_seconds=60) + with pytest.raises(ValueError): + store.query_metric_samples(host_scope(HOST), "not-uuid", since=0, until=1, + interval_seconds=60) + + +def test_collector_prunes_when_ssh_locked_and_starts_after_db_configuration(): + class Store: + def __init__(self): + self.pruned = [] + self.saved = [] + self.pruned_event = threading.Event() + self.saved_event = threading.Event() + + def prune_metric_samples(self, cutoff): + self.pruned.append(cutoff) + self.pruned_event.set() + return 0 + + def save_metric_samples(self, scope, points): + self.saved.append((scope, points)) + self.saved_event.set() + + current = {"store": None, "profile": None} + store = Store() + class Service: + def metric_counters(self): + return [raw()] + collector = MetricsCollector(lambda: current["store"], + lambda: current["profile"], + lambda _profile: Service(), interval_seconds=0.01) + collector.start() + current["profile"] = {**HOST, "key_locked": True} + current["store"] = store + try: + assert store.pruned_event.wait(timeout=2) + assert store.pruned and not store.saved + current["profile"]["key_locked"] = False + assert store.saved_event.wait(timeout=2) + assert store.saved + finally: + collector.close() + + +def test_background_collector_keeps_sampling_without_an_http_session(): + """The 30-day history must not depend on a logged-in browser polling it.""" + saved_twice = threading.Event() + + class Store: + def __init__(self): + self.saved = [] + + def save_metric_samples(self, scope, points): + self.saved.append((scope, points)) + if len(self.saved) >= 2: + saved_twice.set() + + def prune_metric_samples(self, _cutoff): + return 0 + + class Service: + calls = 0 + + def metric_counters(self): + self.calls += 1 + return [raw(cpu=self.calls * 1_000_000_000, + block_read=self.calls * 1000, + network_rx=self.calls * 1000)] + + store = Store() + service = Service() + profile = {**HOST, "key_locked": False} + collector = MetricsCollector(lambda: store, lambda: profile, + lambda _profile: service, + interval_seconds=0.01) + collector.start() + try: + assert saved_twice.wait(timeout=2) + finally: + collector.close() + + assert service.calls >= 2 + assert all(scope == host_scope(HOST) for scope, _ in store.saved) + assert all(points[0]["vm_id"] == VM_ID for _, points in store.saved) + + +def test_metric_cleanup_failure_does_not_discard_current_sample(caplog): + events = [] + attempted = threading.Event() + + class Store: + def save_metric_samples(self, _scope, points): + events.append(("saved", points)) + + def prune_metric_samples(self, _cutoff): + events.append(("prune", None)) + attempted.set() + raise RuntimeError("secret database details") + + class Service: + def metric_counters(self): + return [raw()] + + collector = MetricsCollector(lambda: Store(), lambda: HOST, + lambda _profile: Service(), interval_seconds=1) + collector.start() + assert attempted.wait(timeout=2) + collector.close() + assert [event[0] for event in events] == ["saved", "prune"] + assert "RuntimeError" in caplog.text + assert "secret database details" not in caplog.text + + +def test_backlog_cleanup_continues_in_other_thread_without_stalling_samples(): + second_saved = threading.Event() + prune_entered = threading.Event() + release_prune = threading.Event() + backlog_drained = threading.Event() + + class Store: + def __init__(self): + self.saved = 0 + self.pruned = 0 + + def save_metric_samples(self, _scope, _points): + self.saved += 1 + if self.saved >= 2: + second_saved.set() + + def prune_metric_samples(self, _cutoff): + self.pruned += 1 + if self.pruned == 1: + prune_entered.set() + assert release_prune.wait(timeout=2) + if self.pruned < 3: + return 5000 + backlog_drained.set() + return 0 + + class Service: + def metric_counters(self): + return [raw()] + + store = Store() + collector = MetricsCollector(lambda: store, lambda: HOST, + lambda _profile: Service(), interval_seconds=0.01) + collector.start() + try: + assert prune_entered.wait(timeout=2) + assert second_saved.wait(timeout=2) + release_prune.set() + assert backlog_drained.wait(timeout=2) + assert store.pruned >= 3 + finally: + release_prune.set() + collector.close() + + +def test_collector_thread_starts_before_db_configuration_and_stops(): + ready = threading.Event() + current = {"store": None} + + class Store: + def prune_metric_samples(self, _cutoff): + ready.set() + return 0 + + collector = MetricsCollector(lambda: current["store"], lambda: None, + lambda _profile: pytest.fail("no host configured"), + interval_seconds=0.01) + collector.start() + current["store"] = Store() + assert ready.wait(timeout=2) + collector.close() + assert collector._thread is not None and not collector._thread.is_alive() + assert collector._prune_thread is not None and not collector._prune_thread.is_alive() diff --git a/engine/tests/test_panel_state.py b/engine/tests/test_panel_state.py new file mode 100644 index 00000000..9c7369a3 --- /dev/null +++ b/engine/tests/test_panel_state.py @@ -0,0 +1,111 @@ +"""Persistent setup state and one-time token safety checks.""" + +from __future__ import annotations + +import os +import stat +from concurrent.futures import ThreadPoolExecutor + +import pytest + +from virsh_panel.auth import verify_password +from virsh_panel.panel_state import PanelState, SetupError + + +def test_token_is_reused_before_setup_and_removed_after_setup(tmp_path): + state = PanelState(tmp_path / "panel-data") + first = state.initialize_setup_token() + assert first and len(first) >= 32 + assert state.initialize_setup_token() == first + assert stat.S_IMODE(state.token_file.stat().st_mode) == 0o600 + assert stat.S_IMODE(state.data_dir.stat().st_mode) == 0o700 + + with pytest.raises(SetupError) as invalid: + state.create_admin("invalid", "admin", "correct-horse-battery-staple") + assert invalid.value.status == 403 + assert state.setup_required() + + assert state.create_admin(first, "admin", "correct-horse-battery-staple") == "admin" + assert not state.token_file.exists() + assert stat.S_IMODE(state.state_file.stat().st_mode) == 0o600 + restarted = PanelState(state.data_dir) + username, encoded = restarted.admin() + assert username == "admin" + assert verify_password("correct-horse-battery-staple", encoded) + assert restarted.initialize_setup_token() is None + with pytest.raises(SetupError) as duplicate: + restarted.create_admin(first, "admin", "another-good-password") + assert duplicate.value.status == 409 + + +def test_rejects_public_data_dir_and_setup_token(tmp_path): + data_dir = tmp_path / "public-data" + data_dir.mkdir(mode=0o755) + os.chmod(data_dir, 0o755) + with pytest.raises(ValueError, match="private directory"): + PanelState(data_dir) + + state = PanelState(tmp_path / "private-data") + state.initialize_setup_token() + os.chmod(state.token_file, 0o644) + with pytest.raises(ValueError, match="private"): + state.initialize_setup_token() + + +def test_systemd_style_parent_symlink_is_supported_but_final_symlink_is_not(tmp_path): + private_parent = tmp_path / "private" / "virsh-panel" + private_parent.mkdir(parents=True, mode=0o700) + public_alias = tmp_path / "virsh-panel" + public_alias.symlink_to(private_parent, target_is_directory=True) + + state = PanelState(public_alias / "state") + assert state.data_dir == private_parent / "state" + assert state.initialize_setup_token() + + final_alias = tmp_path / "state-alias" + final_alias.symlink_to(state.data_dir, target_is_directory=True) + with pytest.raises(ValueError, match="symlink"): + PanelState(final_alias) + + +def test_concurrent_process_style_initialization_reuses_one_token(tmp_path): + data_dir = tmp_path / "panel-data" + + def start_panel(_index): + return PanelState(data_dir).initialize_setup_token() + + with ThreadPoolExecutor(max_workers=8) as workers: + tokens = list(workers.map(start_panel, range(16))) + assert len(set(tokens)) == 1 + assert stat.S_IMODE((data_dir / ".setup.lock").stat().st_mode) == 0o600 + + +def test_concurrent_admin_creation_has_one_winner(tmp_path): + data_dir = tmp_path / "panel-data" + token = PanelState(data_dir).initialize_setup_token() + + def create(index): + try: + return PanelState(data_dir).create_admin( + token, f"admin{index}", "correct-horse-battery-staple" + ) + except SetupError as exc: + return exc.status + + with ThreadPoolExecutor(max_workers=2) as workers: + results = list(workers.map(create, range(2))) + assert sorted(str(item) for item in results) in ( + ["409", "admin0"], ["409", "admin1"], + ) + assert not (data_dir / "setup-token").exists() + + +def test_stale_token_after_admin_write_is_not_relogged(tmp_path): + state = PanelState(tmp_path / "panel-data") + token = state.initialize_setup_token() + state.create_admin(token, "admin", "correct-horse-battery-staple") + # Emulate power loss between the atomic admin write and token removal. + state.token_file.write_text(token + "\n", encoding="ascii") + os.chmod(state.token_file, 0o600) + assert PanelState(state.data_dir).initialize_setup_token() is None + assert not state.token_file.exists() diff --git a/engine/tests/test_public_ip_pool.py b/engine/tests/test_public_ip_pool.py new file mode 100644 index 00000000..c5cb5bc4 --- /dev/null +++ b/engine/tests/test_public_ip_pool.py @@ -0,0 +1,112 @@ +"""Validation of a host's public IPv4 allocation range.""" + +from __future__ import annotations + +import pytest + +from virsh_panel.remote_host import RemoteHostError, validate_public_pool + + +_DEFAULT = object() + + +def validate(cidr="1.2.3.0/24", gateway="1.2.3.1", dns=_DEFAULT, reserved=_DEFAULT, + vm_prefix=None): + return validate_public_pool( + cidr, + gateway, + ["1.1.1.1", "8.8.8.8"] if dns is _DEFAULT else dns, + [] if reserved is _DEFAULT else reserved, + "1.2.3.2", + vm_prefix, + ) + + +def test_unconfigured_public_pool_has_empty_defaults(): + assert validate_public_pool("", "", [], [], "host.example") == { + "public_pool_cidr": "", + "public_gateway": "", + "public_dns_servers": [], + "public_reserved_ips": [], + "public_vm_prefix": None, + } + with pytest.raises(RemoteHostError): + validate_public_pool("", "", [], [], "host.example", 24) + + +def test_public_pool_normalizes_and_deduplicates_addresses(): + assert validate( + dns=["1.1.1.1", "1.1.1.1", "8.8.8.8"], + reserved=["1.2.3.10", "1.2.3.10", "1.2.3.20"], + ) == { + "public_pool_cidr": "1.2.3.0/24", + "public_gateway": "1.2.3.1", + "public_dns_servers": ["1.1.1.1", "8.8.8.8"], + "public_reserved_ips": ["1.2.3.10", "1.2.3.20"], + "public_vm_prefix": None, + } + + +@pytest.mark.parametrize("cidr", ["123.123.123.112/28", "123.123.123.113/28"]) +def test_provider_28_is_normalized_without_widening_to_24(cidr): + configured = validate( + cidr, "123.123.123.113", ["1.1.1.1"], + ["123.123.123.114", "123.123.123.126"], + ) + assert configured["public_pool_cidr"] == "123.123.123.112/28" + assert configured["public_gateway"] == "123.123.123.113" + assert configured["public_reserved_ips"] == [ + "123.123.123.114", "123.123.123.126", + ] + + +def test_guest_mask_can_be_24_while_allocation_remains_28(): + configured = validate("123.123.123.112/28", "123.123.123.113", + ["1.1.1.1"], [], vm_prefix=24) + assert configured["public_pool_cidr"] == "123.123.123.112/28" + assert configured["public_vm_prefix"] == 24 + + +@pytest.mark.parametrize("prefix", [23, 29, 31, True, "24"]) +def test_guest_mask_rejects_values_outside_pool_bounds(prefix): + with pytest.raises(RemoteHostError): + validate("123.123.123.112/28", "123.123.123.113", + ["1.1.1.1"], [], vm_prefix=prefix) + + +@pytest.mark.parametrize( + ("cidr", "gateway", "dns", "reserved"), + [ + ("1.2.3.0/24", "", ["1.1.1.1"], []), + ("", "1.2.3.1", ["1.1.1.1"], []), + ("1.2.3.0/24", "1.2.3.1", [], []), + ("", "", [], ["1.2.3.10"]), + ("1.2.3.1/24", "1.2.3.1", ["1.1.1.1"], []), + ("1.2.2.0/23", "1.2.3.1", ["1.1.1.1"], []), + ("1.2.3.0/31", "1.2.3.1", ["1.1.1.1"], []), + ("123.123.123.112/28", "123.123.123.111", ["1.1.1.1"], []), + ("123.123.123.112/28", "123.123.123.127", ["1.1.1.1"], []), + ("123.123.123.112/28", "123.123.123.113", ["1.1.1.1"], ["123.123.123.128"]), + ("10.0.0.0/24", "10.0.0.1", ["1.1.1.1"], []), + ("203.0.113.0/24", "203.0.113.1", ["1.1.1.1"], []), + ("2001:db8::/24", "2001:db8::1", ["1.1.1.1"], []), + ("1.2.3.0/24", "1.2.4.1", ["1.1.1.1"], []), + ("1.2.3.0/24", "1.2.3.0", ["1.1.1.1"], []), + ("1.2.3.0/24", "1.2.3.255", ["1.1.1.1"], []), + ("1.2.3.0/24", "1.2.3.1", ["10.0.0.1"], []), + ("1.2.3.0/24", "1.2.3.1", + ["1.1.1.1", "8.8.8.8", "9.9.9.9", "208.67.222.222", "208.67.220.220"], []), + ("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.4.2"]), + ("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.3.0"]), + ("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.3.255"]), + ], +) +def test_public_pool_rejects_invalid_configuration(cidr, gateway, dns, reserved): + with pytest.raises(RemoteHostError): + validate(cidr, gateway, dns, reserved) + + +@pytest.mark.parametrize("value", [None, "1.1.1.1", ["1.1.1.1", None]]) +def test_dns_must_be_list_of_ip_strings(value): + with pytest.raises(RemoteHostError): + validate(dns=value) diff --git a/engine/tests/test_registration_http.py b/engine/tests/test_registration_http.py new file mode 100644 index 00000000..0b6dbb81 --- /dev/null +++ b/engine/tests/test_registration_http.py @@ -0,0 +1,982 @@ +"""Production database-mode registration and authorization HTTP boundary.""" + +from __future__ import annotations + +import asyncio +import ipaddress +import json +import sys +import time +import types +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient +from starlette.websockets import WebSocketDisconnect + + +try: + import libvirt # noqa: F401 +except ModuleNotFoundError: + stub = types.ModuleType("libvirt") + stub.libvirtError = type("libvirtError", (Exception,), {}) + sys.modules["libvirt"] = stub + +from tests.test_database_http import MemoryStore # noqa: E402 +from virsh_panel import app as app_module # noqa: E402 +from virsh_panel.auth import hash_password # noqa: E402 +from virsh_panel.config import Settings # noqa: E402 +from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore # noqa: E402 +from virsh_panel.libvirt_service import VMError # noqa: E402 +from virsh_panel.metrics import host_scope # noqa: E402 +from virsh_panel.cloud_templates import template_scope # noqa: E402 +from virsh_panel.ssh_keys import SSHKeyError, _name, _public_key # noqa: E402 + + +ORIGIN = "https://panel.example.test" +PASSWORD = "correct-horse-battery-staple" +CREATE_VM = { + "name": "tenant-vm", "vcpu": 2, "memory_mib": 2048, + "disk_gib": 20, "network": "bridge:br0", "iso": "AlmaLinux-10.iso", +} +GUEST_PUBLIC_KEY = ( + "ssh-ed25519 " + "AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 " + "panel-test" +) +CLOUD_VM = { + "source": "cloud", "template_id": "alma10-template", + "name": "tenant-cloud", "vcpu": 2, "memory_mib": 2048, + "disk_gib": 20, "network": "bridge:br0", "public_ip_cidr": "8.8.8.18/24", + "gateway": "8.8.8.1", "dns_servers": ["1.1.1.1"], +} + + +class _MemorySSHKeys: + """Mimic the owner-scoped SQL boundary for production-mode HTTP tests.""" + + def __init__(self): + self.rows = {} + self.next_id = 1 + + def list_for_user(self, user_id): + return [row.copy() for owner, row in self.rows.values() if owner == user_id] + + def create_for_user(self, user_id, name, public_key): + name = _name(name) + public_key, fingerprint = _public_key(public_key) + if any(owner == user_id and row["fingerprint"] == fingerprint + for owner, row in self.rows.values()): + raise SSHKeyError("此 SSH 公钥已添加到当前账户", 409) + key_id = self.next_id + self.next_id += 1 + row = {"id": key_id, "name": name, "public_key": public_key, + "fingerprint": fingerprint, "created_at": 100} + self.rows[key_id] = (user_id, row) + return row.copy() + + def get_for_user(self, user_id, key_id): + found = self.rows.get(key_id) + return found[1].copy() if found is not None and found[0] == user_id else None + + def delete_for_user(self, user_id, key_id): + if self.get_for_user(user_id, key_id) is None: + return False + del self.rows[key_id] + return True + + +class _Manager: + profile = { + "host": "vmhost.example.test", "port": 22, + "fingerprint": "SHA256:configured-host", "key_locked": False, + "region": "东京", "storage_pool": "/home/kvm", "iso_pool": "/home/iso", + "default_network": "bridge:br0", "ssh_target": "vp-managed", + "ssh_config_file": "/fake/config", "ssh_known_hosts_file": "/fake/known_hosts", + } + + def current(self): + return self.profile + + def close(self): + pass + + +class _Service: + def __init__(self): + self.vms = {} + self.console_calls = [] + self.cloud_specs = [] + self.reinstall_specs = [] + + def create_vm(self, spec): + vm = { + "uuid": spec["vm_uuid"], "name": spec["name"], "state": "running", + "vcpu": spec["vcpu"], "memory_mib": spec["memory_mib"], + "disks": [], "autostart": True, + } + self.vms[vm["uuid"]] = vm + return vm + + def create_cloud_vm(self, spec, volume_name): + self.cloud_specs.append((spec.copy(), volume_name)) + vm = self.create_vm(spec) + vm.update({ + "managed": True, + "os_source": "cloud_template", + "public_ip_cidr": spec["public_ip_cidr"], + "credential_generation": f"panel-seed-{vm['uuid']}.iso", + }) + return vm + + def reinstall_cloud_vm(self, vm_id, volume_name, *, os_name=None, + ssh_public_key="", root_password_hash=None, + progress=None): + vm = self.get_vm(vm_id) + self.reinstall_specs.append((vm_id, volume_name, ssh_public_key, + root_password_hash, os_name)) + if progress is not None: + progress("completed") + generation = f"panel-seed-reinstall-{vm_id}.iso" + vm["credential_generation"] = generation + return {"vm": vm, "credential_generation": generation} + + def resources(self): + return {"networks": ["bridge:br0"], "isos": [], "storage_pool": "/home/kvm"} + + def list_vms(self): + return list(self.vms.values()) + + def get_vm(self, vm_id): + if vm_id not in self.vms: + raise VMError("虚拟机不存在", 404) + return self.vms[vm_id] + + def action(self, vm_id, _action): + return self.get_vm(vm_id) + + def delete_vm(self, vm_id, _delete_disks): + self.get_vm(vm_id) + del self.vms[vm_id] + return {"uuid": vm_id, "deleted": True, "deleted_disks": []} + + def console_port(self, vm_id): + self.console_calls.append(vm_id) + self.get_vm(vm_id) + return 5907 + + +class _NoMetrics: + def __init__(self, *_args, **_kwargs): + pass + + def start(self): + pass + + def close(self): + pass + + +def _login(client: TestClient, email: str): + response = client.post("/api/v1/login", json={ + "email": email, "password": PASSWORD, + }) + assert response.status_code == 200 + return {"X-CSRF-Token": response.json()["csrf_token"]} + + +def _register(client: TestClient, address: str, username: str): + code = client.post("/api/v1/register/code", json={"email": address}) + assert code.status_code == 200 and code.json() == {"sent": True} + response = client.post("/api/v1/register", json={ + "username": username, "email": address, + "password": PASSWORD, "code": "123456", + }) + assert response.status_code == 201 + assert response.json() == {"registered": True, "approved": False} + + +def test_template_rename_is_admin_only_and_ordinary_users_can_list(monkeypatch, tmp_path): + store = MemoryStore() + service = _Service() + monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( + DatabasePanelState(directory, store, store.users), _Manager(), + DatabaseTemplateStore(store), store, + )) + monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics) + settings = Settings( + data_dir=tmp_path / "data", + static_dir=Path(__file__).resolve().parents[1] / "static", + ) + app = app_module.create_app(settings, service_factory=lambda _profile: service) + token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip() + scope = template_scope(_Manager.profile) + template_id = "alma9-12345678-abcdef0123456789" + record = { + "id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux", + "os_version": "9", "sha256": "f" * 64, + "volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2", + } + endpoint = f"/api/v1/vm-templates/{template_id}" + + with TestClient(app, base_url=ORIGIN) as admin: + assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 401 + configured = admin.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "database-password", "setup_token": token, + }) + assert configured.status_code == 200 + created = admin.post("/api/v1/setup/admin", json={ + "token": token, "username": "initial", "password": PASSWORD, + }) + assert created.status_code == 200 + admin_headers = {"X-CSRF-Token": created.json()["csrf_token"]} + templates = DatabaseTemplateStore(store) + templates.add(scope, record) + templates.add(scope, {**record, "id": "another", "name": "Other template"}) + templates.add("b" * 64, {**record, "name": "Different host"}) + assert admin.patch(endpoint, json={"name": "Rename"}, + headers=admin_headers).status_code == 403 + store.users.promote("initial") + + store.set("test_user", "tenant", json.dumps({ + "id": 2, "username": "tenant", "email": "tenant@example.test", + "password_hash": hash_password(PASSWORD), "admin": False, + "approved": True, "email_verified": True, "created_at": 100, + })) + with TestClient(app, base_url=ORIGIN) as tenant: + tenant_headers = _login(tenant, "tenant@example.test") + listed = tenant.get("/api/v1/vm-templates") + assert listed.status_code == 200 + assert [row["id"] for row in listed.json()["templates"]] == [ + template_id, "another", + ] + assert tenant.patch(endpoint, json={"name": "Hijack"}, + headers=tenant_headers).status_code == 403 + assert tenant.post("/api/v1/vm-templates/import", json={ + "name": "Extra", "url": "https://invalid.example/image.qcow2", + "sha256": "a" * 64, + }, headers=tenant_headers).status_code == 403 + + assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 403 + assert admin.patch(endpoint, json={"name": "Other TEMPLATE"}, + headers=admin_headers).status_code == 409 + assert admin.patch(endpoint, json={"name": " "}, + headers=admin_headers).status_code == 400 + missing = admin.patch("/api/v1/vm-templates/missing", json={"name": "Missing"}, + headers=admin_headers) + assert missing.status_code == 404 + renamed = admin.patch(endpoint, json={"name": " AlmaLinux 9 Gold "}, + headers=admin_headers) + assert renamed.status_code == 200 + assert renamed.json()["template"] == {**record, "name": "AlmaLinux 9 Gold"} + assert DatabaseTemplateStore(store).get(scope, template_id) == renamed.json()["template"] + assert templates.get("b" * 64, template_id)["name"] == "Different host" + + +def test_registration_smtp_approval_and_per_user_vm_isolation(monkeypatch, tmp_path): + store = MemoryStore() + service = _Service() + sent = [] + monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( + DatabasePanelState(directory, store, store.users), _Manager(), + DatabaseTemplateStore(store), store, + )) + monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics) + monkeypatch.setattr( + app_module, "send_verification_code", + lambda config, email, code: sent.append((config.host, email, code)), + ) + settings = Settings( + data_dir=tmp_path / "data", + static_dir=Path(__file__).resolve().parents[1] / "static", + ) + app = app_module.create_app(settings, service_factory=lambda _profile: service) + token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip() + + with TestClient(app, base_url=ORIGIN) as admin: + configured = admin.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "database-password", "setup_token": token, + }) + assert configured.status_code == 200 + initial = admin.post("/api/v1/setup/admin", json={ + "token": token, "username": "firstuser", "password": PASSWORD, + }) + assert initial.status_code == 200 + admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]} + assert admin.get("/api/v1/session").json()["admin"] is False + assert admin.get("/api/v1/smtp/settings").status_code == 403 + # The operator promotes the initial account and adds its email in MariaDB. + store.users.promote("firstuser") + assert admin.get("/api/v1/session").json()["admin"] is True + initial_account = store.users.get_by_username("firstuser") + assert initial_account["email"] is None + with TestClient(app, base_url=ORIGIN) as missing_email: + assert missing_email.post("/api/v1/login", json={ + "email": "first@example.test", "password": PASSWORD, + }).status_code == 401 + store.set("test_user", "firstuser", json.dumps({ + **initial_account, "email": "first@example.test", + })) + with TestClient(app, base_url=ORIGIN) as fresh_admin: + assert fresh_admin.post("/api/v1/login", json={ + "username": "firstuser", "password": PASSWORD, + }).status_code == 422 + assert fresh_admin.post("/api/v1/login", json={ + "email": "firstuser", "password": PASSWORD, + }).status_code == 401 + assert _login(fresh_admin, "FIRST@EXAMPLE.TEST") + assert fresh_admin.get("/api/v1/session").json()["admin"] is True + smtp = admin.put("/api/v1/smtp/settings", json={ + "host": "smtp.example.test", "port": 587, "tls_mode": "starttls", + "from_address": "panel@example.test", "username": "mailer", + "password": "smtp-secret-password", + }, headers=admin_headers) + assert smtp.status_code == 200 + assert "smtp-secret-password" not in smtp.text + + original_sender = app_module.send_verification_code + + def fail_delivery(_config, _email, _code): + raise app_module.SMTPError("模拟 SMTP 发送失败", 502) + + monkeypatch.setattr(app_module, "send_verification_code", fail_delivery) + with TestClient(app, base_url=ORIGIN) as visitor: + failed_send = visitor.post("/api/v1/register/code", json={ + "email": "delivery-fail@example.test", + }) + assert failed_send.status_code == 200 + assert failed_send.json() == {"sent": True} + # A failed background delivery must remove the challenge so the + # user is not trapped behind the resend cooldown. + assert store.get("test_code", "delivery-fail@example.test") is None + monkeypatch.setattr(app_module, "send_verification_code", original_sender) + with TestClient(app, base_url=ORIGIN) as visitor: + retried = visitor.post("/api/v1/register/code", json={ + "email": "delivery-fail@example.test", + }) + assert retried.status_code == failed_send.status_code + assert retried.json() == failed_send.json() + assert store.get("test_code", "delivery-fail@example.test") == "123456" + sent.clear() + + with TestClient(app, base_url=ORIGIN) as first: + _register(first, "one@example.test", "tenantone") + assert sent == [("smtp.example.test", "one@example.test", "123456")] + first_headers = _login(first, "ONE@EXAMPLE.TEST") + assert first.get("/api/v1/session").json()["approved"] is False + assert first.post("/api/v1/vms", json=CREATE_VM, + headers=first_headers).status_code == 403 + for protected in ( + "/api/v1/host", "/api/v1/update/settings", + "/api/v1/smtp/settings", "/api/v1/users/pending", + ): + assert first.get(protected).status_code == 403 + pending = admin.get("/api/v1/users/pending") + assert pending.status_code == 200 + items = pending.json()["items"] + assert len(items) == 1 and items[0]["username"] == "tenantone" + assert "password_hash" not in items[0] + approve = admin.post(f"/api/v1/users/{items[0]['id']}/approve", + headers=admin_headers) + assert approve.status_code == 200 + assert first.get("/api/v1/session").json()["approved"] is True + own = first.post("/api/v1/vms", json=CREATE_VM, headers=first_headers) + assert own.status_code == 201 + own_id = own.json()["uuid"] + + with TestClient(app, base_url=ORIGIN) as second: + _register(second, "two@example.test", "tenanttwo") + second_headers = _login(second, "two@example.test") + second_id = store.users.get_by_username("tenanttwo")["id"] + assert admin.post(f"/api/v1/users/{second_id}/approve", + headers=admin_headers).status_code == 200 + other = second.post("/api/v1/vms", json={**CREATE_VM, "name": "other-vm"}, + headers=second_headers) + assert other.status_code == 201 + other_id = other.json()["uuid"] + + assert [vm["uuid"] for vm in first.get("/api/v1/vms").json()["items"]] == [own_id] + assert [vm["uuid"] for vm in second.get("/api/v1/vms").json()["items"]] == [other_id] + assert len(admin.get("/api/v1/vms").json()["items"]) == 2 + assert first.get(f"/api/v1/vms/{other_id}").status_code == 404 + assert first.post(f"/api/v1/vms/{other_id}/credential", + headers=first_headers).status_code == 404 + assert first.get(f"/api/v1/vms/{other_id}/metrics").status_code == 404 + assert first.post(f"/api/v1/vms/{other_id}/actions", json={ + "action": "reboot", + }, headers=first_headers).status_code == 404 + assert first.delete(f"/api/v1/vms/{other_id}", + headers=first_headers).status_code == 404 + assert first.get(f"/api/v1/vms/{own_id}").status_code == 200 + assert first.get("/api/v1/host").status_code == 403 + assert first.put("/api/v1/update/settings", json={ + "repository_url": "https://g.luoli.live/root/virt.git", "branch": "main", + "access_token": "forbidden", + }, headers=first_headers).status_code == 403 + assert first.put("/api/v1/smtp/settings", json={ + "host": "evil.example.test", "port": 587, "tls_mode": "starttls", + "from_address": "evil@example.test", + }, headers=first_headers).status_code == 403 + assert first.post(f"/api/v1/users/{second_id}/approve", + headers=first_headers).status_code == 403 + + cookie = first.cookies.get("virsh_panel_session") + with pytest.raises(WebSocketDisconnect) as denied: + with first.websocket_connect( + f"wss://panel.example.test/api/v1/vms/{other_id}/console", + headers={ + "host": "panel.example.test", "origin": ORIGIN, + "cookie": f"virsh_panel_session={cookie}", + }, + ): + pass + assert denied.value.code == 4404 + assert service.console_calls == [] + + monkeypatch.setattr(app_module, "CONSOLE_ACCESS_CHECK_SECONDS", 0.05) + + async def held_console(_websocket, **_kwargs): + # If the watchdog fails to close promptly, the relay + # closes with 1011 after a bounded fallback delay. + await asyncio.sleep(1) + raise app_module.ConsoleRelayError("test relay timeout") + + monkeypatch.setattr(app_module, "relay_console", held_console) + own_console = f"wss://panel.example.test/api/v1/vms/{own_id}/console" + own_cookie = first.cookies.get("virsh_panel_session") + with first.websocket_connect(own_console, headers={ + "host": "panel.example.test", "origin": ORIGIN, + "cookie": f"virsh_panel_session={own_cookie}", + }) as console: + assert first.post("/api/v1/logout", headers=first_headers).status_code == 200 + with pytest.raises(WebSocketDisconnect) as revoked: + console.receive_text() + assert revoked.value.code == 4403 + + first_headers = _login(first, "one@example.test") + own_cookie = first.cookies.get("virsh_panel_session") + with first.websocket_connect(own_console, headers={ + "host": "panel.example.test", "origin": ORIGIN, + "cookie": f"virsh_panel_session={own_cookie}", + }) as console: + store.users.delete_vm_owner(host_scope(_Manager.profile), own_id) + with pytest.raises(WebSocketDisconnect) as ownership_revoked: + console.receive_text() + assert ownership_revoked.value.code == 4403 + + # A deleted username may later be reused. Its old bearer + # cookie must not acquire the replacement account's role. + old_account = store.users.get_by_username("tenantone") + store.delete("test_user", "tenantone") + replacement = {**old_account, "id": old_account["id"] + 1000, + "admin": True} + store.set("test_user", "tenantone", json.dumps(replacement)) + assert first.get("/api/v1/session").json()["authenticated"] is False + assert first.get("/api/v1/smtp/settings").status_code == 401 + assert first.post("/api/v1/vms", json=CREATE_VM, + headers=first_headers).status_code == 401 + + +def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path): + store = MemoryStore() + key_store = _MemorySSHKeys() + service = _Service() + + def components(directory, *_args): + state = DatabasePanelState(directory, store, store.users) + state.ssh_keys = key_store + return state, _Manager(), DatabaseTemplateStore(store), store + + monkeypatch.setattr(app_module, "make_components", components) + monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics) + settings = Settings( + data_dir=tmp_path / "data", + static_dir=Path(__file__).resolve().parents[1] / "static", + ) + app = app_module.create_app(settings, service_factory=lambda _profile: service) + token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip() + + with TestClient(app, base_url=ORIGIN) as admin: + assert admin.get("/api/v1/ssh-keys").status_code == 401 + assert admin.post("/api/v1/ssh-keys", json={ + "name": "initial", "public_key": GUEST_PUBLIC_KEY, + }).status_code == 401 + assert admin.delete("/api/v1/ssh-keys/1").status_code == 401 + assert admin.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "database-password", "setup_token": token, + }).status_code == 200 + initial = admin.post("/api/v1/setup/admin", json={ + "token": token, "username": "firstuser", "password": PASSWORD, + }) + assert initial.status_code == 200 + admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]} + store.users.promote("firstuser") + DatabaseTemplateStore(store).add(template_scope(_Manager.profile), { + "id": "alma10-template", "name": "AlmaLinux 10", + "volume_name": "panel-template-alma10.qcow2", + }) + + # Even an administrator has a personal key library, not every + # tenant's keys. No private-key content is accepted by the API. + assert admin.get("/api/v1/ssh-keys").json() == {"items": []} + rejected_private = admin.post("/api/v1/ssh-keys", json={ + "name": "wrong", "public_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nsecret", + }, headers=admin_headers) + assert rejected_private.status_code in (400, 422) + + store.users.issue_registration_code("one@example.test", "123456") + first_account = store.users.register_with_code( + "tenantone", "one@example.test", PASSWORD, "123456", + ) + store.users.issue_registration_code("two@example.test", "123456") + second_account = store.users.register_with_code( + "tenanttwo", "two@example.test", PASSWORD, "123456", + ) + + with TestClient(app, base_url=ORIGIN) as first, \ + TestClient(app, base_url=ORIGIN) as second: + first_headers = _login(first, "one@example.test") + second_headers = _login(second, "two@example.test") + assert first.get("/api/v1/session").json()["approved"] is False + assert first.get("/api/v1/ssh-keys").json() == {"items": []} + assert first.post("/api/v1/ssh-keys", json={ + "name": "laptop", "public_key": GUEST_PUBLIC_KEY, + }).status_code == 403 + imported = first.post("/api/v1/ssh-keys", json={ + "name": "laptop", "public_key": GUEST_PUBLIC_KEY, + }, headers=first_headers) + assert imported.status_code == 201 + first_key = imported.json() + assert first_key["name"] == "laptop" + assert first_key["public_key"].startswith("ssh-ed25519 ") + assert first_key["fingerprint"].startswith("SHA256:") + assert isinstance(first_key["id"], int) + assert first.post("/api/v1/ssh-keys", json={ + "name": "duplicate comment", "public_key": GUEST_PUBLIC_KEY, + }, headers=first_headers).status_code == 409 + assert first.get("/api/v1/ssh-keys").json()["items"] == [first_key] + assert second.get("/api/v1/ssh-keys").json() == {"items": []} + assert admin.get("/api/v1/ssh-keys").json() == {"items": []} + assert first.post("/api/v1/vms", json={ + **CLOUD_VM, "guest_ssh_key_id": first_key["id"], + }, headers=first_headers).status_code == 403 + + # The same public key is allowed in another account, but its + # record has a different ID and remains independently owned. + second_import = second.post("/api/v1/ssh-keys", json={ + "name": "other laptop", "public_key": GUEST_PUBLIC_KEY, + }, headers=second_headers) + assert second_import.status_code == 201 + second_key = second_import.json() + assert second_key["id"] != first_key["id"] + assert second.get("/api/v1/ssh-keys").json()["items"] == [second_key] + assert second.delete(f"/api/v1/ssh-keys/{first_key['id']}", + headers=second_headers).status_code == 404 + assert first.delete("/api/v1/ssh-keys/-1", + headers=first_headers).status_code == 404 + assert admin.delete(f"/api/v1/ssh-keys/{first_key['id']}", + headers=admin_headers).status_code == 404 + assert first.get("/api/v1/ssh-keys").json()["items"] == [first_key] + + assert admin.post(f"/api/v1/users/{first_account['id']}/approve", + headers=admin_headers).status_code == 200 + assert admin.post(f"/api/v1/users/{second_account['id']}/approve", + headers=admin_headers).status_code == 200 + before = len(service.cloud_specs) + for client, headers, forbidden_id in ( + (first, first_headers, second_key["id"]), + (second, second_headers, first_key["id"]), + (admin, admin_headers, first_key["id"]), + ): + forbidden = client.post("/api/v1/vms", json={ + **CLOUD_VM, "guest_ssh_key_id": forbidden_id, + }, headers=headers) + assert forbidden.status_code == 404 + missing = first.post("/api/v1/vms", json={ + **CLOUD_VM, "guest_ssh_key_id": 999999, + }, headers=first_headers) + assert missing.status_code == 404 + for conflicting in ( + {"guest_ssh_key_id": first_key["id"], + "guest_ssh_public_key": GUEST_PUBLIC_KEY}, + ): + response = first.post("/api/v1/vms", json={ + **CLOUD_VM, **conflicting, + }, headers=first_headers) + assert response.status_code == 422 + assert len(service.cloud_specs) == before + + selected = first.post("/api/v1/vms", json={ + **CLOUD_VM, "guest_ssh_key_id": first_key["id"], + "root_password": "A-strong-guest-password-2026", + }, headers=first_headers) + assert selected.status_code == 201 + spec, _volume = service.cloud_specs[-1] + assert spec["guest_ssh_public_key"] == first_key["public_key"] + assert "guest_ssh_key_id" not in spec + assert spec["root_password_hash"].startswith("$6$") + assert selected.json()["auth_mode"] == "ssh_key_password" + assert selected.json()["password_available"] + assert first.post( + f"/api/v1/vms/{selected.json()['uuid']}/credential", + headers=first_headers, + ).json()["password"] == "A-strong-guest-password-2026" + assert second.get(f"/api/v1/vms/{selected.json()['uuid']}").status_code == 404 + + key_with_generated_password = first.post("/api/v1/vms", json={ + **CLOUD_VM, "name": "saved-key-auto-password", + "public_ip_cidr": "8.8.8.21/24", + "guest_ssh_key_id": first_key["id"], + "root_password": "", + }, headers=first_headers) + assert key_with_generated_password.status_code == 201 + key_spec, _key_volume = service.cloud_specs[-1] + assert key_spec["guest_ssh_public_key"] == first_key["public_key"] + assert key_spec["root_password_hash"].startswith("$6$") + assert key_with_generated_password.json()["auth_mode"] == "ssh_key_password" + assert key_with_generated_password.json()["password_available"] + key_credential = first.post( + f"/api/v1/vms/{key_with_generated_password.json()['uuid']}/credential", + headers=first_headers, + ).json() + assert key_credential["auth_mode"] == "ssh_key_password" + assert len(key_credential["password"]) >= 24 + assert any(c.isupper() for c in key_credential["password"]) + assert any(c.islower() for c in key_credential["password"]) + assert any(not c.isalnum() and not c.isspace() + for c in key_credential["password"]) + from passlib.hash import sha512_crypt + assert sha512_crypt.verify( + key_credential["password"], key_spec["root_password_hash"], + ) + assert key_credential["password"] not in key_with_generated_password.text + assert key_credential["password"] not in repr(service.cloud_specs) + assert second.get( + f"/api/v1/vms/{key_with_generated_password.json()['uuid']}" + ).status_code == 404 + + reinstall_url = f"/api/v1/vms/{selected.json()['uuid']}/reinstall" + reinstall_body = {"template_id": "alma10-template", + "confirmation_name": "tenant-cloud"} + for client, headers, key_id in ( + (first, first_headers, second_key["id"]), + (admin, admin_headers, first_key["id"]), + ): + assert client.post(reinstall_url, json={ + **reinstall_body, "ssh_key_id": key_id, + }, headers=headers).status_code == 404 + assert second.post(reinstall_url, json={ + **reinstall_body, "ssh_key_id": second_key["id"], + }, headers=second_headers).status_code == 404 + assert first.post(reinstall_url, json={ + **reinstall_body, "ssh_key_id": first_key["id"], + "ssh_public_key": GUEST_PUBLIC_KEY, + }, headers=first_headers).status_code == 422 + assert service.reinstall_specs == [] + + queued = first.post(reinstall_url, json={ + **reinstall_body, "ssh_key_id": first_key["id"], + "root_password": "A-strong-guest-password-2026", + }, headers=first_headers) + assert queued.status_code == 202 + for _ in range(100): + job = first.get(f"/api/v1/reinstall-jobs/{queued.json()['job_id']}", + headers=first_headers) + assert job.status_code == 200 + if job.json()["status"] != "queued" and job.json()["status"] != "running": + break + time.sleep(0.01) + assert job.json()["status"] == "succeeded" + assert service.reinstall_specs[-1][2] == first_key["public_key"] + assert service.reinstall_specs[-1][3].startswith("$6$") + assert "generated_password" not in job.json() + assert first.post( + f"/api/v1/vms/{selected.json()['uuid']}/credential", + headers=first_headers, + ).json()["password"] == "A-strong-guest-password-2026" + + # Existing create paths continue to accept a one-off pasted key + # or an initial root password without a saved-key ID. + manual = first.post("/api/v1/vms", json={ + **CLOUD_VM, "name": "manual-key-vm", + "public_ip_cidr": "8.8.8.19/24", + "guest_ssh_public_key": GUEST_PUBLIC_KEY, + }, headers=first_headers) + assert manual.status_code == 201 + assert service.cloud_specs[-1][0]["guest_ssh_public_key"] == GUEST_PUBLIC_KEY + manual_claim = f"{host_scope(_Manager.profile)}.8.8.8.19" + assert store.get("ip_claim", manual_claim) is not None + duplicate_manual = first.post("/api/v1/vms", json={ + **CLOUD_VM, "name": "duplicate-manual-ip", + "public_ip_cidr": "8.8.8.19/24", + "guest_ssh_public_key": GUEST_PUBLIC_KEY, + }, headers=first_headers) + assert duplicate_manual.status_code == 409 + assert first.delete(f"/api/v1/vms/{manual.json()['uuid']}", + headers=first_headers).status_code == 200 + assert store.get("ip_claim", manual_claim) is None + password = first.post("/api/v1/vms", json={ + **CLOUD_VM, "name": "password-vm", + "public_ip_cidr": "8.8.8.20/24", + "root_password": "A-strong-guest-password-2026", + }, headers=first_headers) + assert password.status_code == 201 + assert password.json()["auth_mode"] == "password" + + assert first.delete(f"/api/v1/ssh-keys/{first_key['id']}").status_code == 403 + deleted = first.delete(f"/api/v1/ssh-keys/{first_key['id']}", + headers=first_headers) + assert 200 <= deleted.status_code < 300 + assert first.get("/api/v1/ssh-keys").json() == {"items": []} + assert second.get("/api/v1/ssh-keys").json()["items"] == [second_key] + assert first.post("/api/v1/vms", json={ + **CLOUD_VM, "name": "deleted-key-vm", + "guest_ssh_key_id": first_key["id"], + }, headers=first_headers).status_code == 404 + assert first.post(reinstall_url, json={ + **reinstall_body, "ssh_key_id": first_key["id"], + }, headers=first_headers).status_code == 404 + assert first.get(f"/api/v1/vms/{selected.json()['uuid']}").status_code == 200 + + +def test_host_public_pool_allocates_globally_and_preserves_tenant_isolation( + monkeypatch, tmp_path, +): + store = MemoryStore() + service = _Service() + manager = _Manager() + manager.profile = { + **_Manager.profile, + "host": "8.8.8.3", + "public_pool_cidr": "8.8.8.0/24", + "public_gateway": "8.8.8.1", + "public_dns_servers": ["1.1.1.1", "8.8.4.4"], + "public_reserved_ips": ["8.8.8.2", "8.8.8.5"], + } + # An existing, panel-visible libvirt guest already occupies one address. + service.vms["00000000-0000-4000-8000-000000000004"] = { + "uuid": "00000000-0000-4000-8000-000000000004", + "name": "existing-vm", "state": "running", "vcpu": 1, + "memory_mib": 1024, "disks": [], "autostart": True, + "public_ip_cidr": "8.8.8.4/24", + } + monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( + DatabasePanelState(directory, store, store.users), manager, + DatabaseTemplateStore(store), store, + )) + monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics) + settings = Settings( + data_dir=tmp_path / "data", + static_dir=Path(__file__).resolve().parents[1] / "static", + ) + app = app_module.create_app(settings, service_factory=lambda _profile: service) + token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip() + automatic_body = { + key: value for key, value in CLOUD_VM.items() + if key not in {"public_ip_cidr", "gateway", "dns_servers"} + } + automatic_body["guest_ssh_public_key"] = GUEST_PUBLIC_KEY + network = ipaddress.ip_network(manager.profile["public_pool_cidr"]) + excluded = {"8.8.8.0", "8.8.8.1", "8.8.8.2", "8.8.8.3", + "8.8.8.4", "8.8.8.5", "8.8.8.6", "8.8.8.255"} + + with TestClient(app, base_url=ORIGIN) as admin: + assert admin.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "database-password", "setup_token": token, + }).status_code == 200 + initial = admin.post("/api/v1/setup/admin", json={ + "token": token, "username": "operator", "password": PASSWORD, + }) + assert initial.status_code == 200 + admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]} + store.users.promote("operator") + DatabaseTemplateStore(store).add(template_scope(manager.profile), { + "id": "alma10-template", "name": "AlmaLinux 10", + "volume_name": "panel-template-alma10.qcow2", + }) + # A claim from another panel worker remains occupied even when its VM + # is not yet visible through libvirt's list API. + pool_scope = host_scope(manager.profile) + assert store.insert("ip_claim", f"{pool_scope}.8.8.8.6", json.dumps({ + "vm_uuid": "00000000-0000-4000-8000-000000000006", + })) + for username in ("tenantone", "tenanttwo"): + email = f"{username}@example.test" + store.users.issue_registration_code(email, "123456") + account = store.users.register_with_code(username, email, PASSWORD, "123456") + assert admin.post(f"/api/v1/users/{account['id']}/approve", + headers=admin_headers).status_code == 200 + + with TestClient(app, base_url=ORIGIN) as first, \ + TestClient(app, base_url=ORIGIN) as second: + first_headers = _login(first, "tenantone@example.test") + second_headers = _login(second, "tenanttwo@example.test") + resources = first.get("/api/v1/resources") + assert resources.status_code == 200 + assert resources.json()["public_pool_enabled"] is True + assert resources.json()["public_pool_cidr"] == "8.8.8.0/24" + assert first.get("/api/v1/host").status_code == 403 + + # Explicit client-side networking cannot bypass the host pool. + for field, value in ( + ("public_ip_cidr", "8.8.8.99/24"), + ("gateway", "8.8.8.1"), + ("dns_servers", ["1.1.1.1"]), + ): + rejected = first.post("/api/v1/vms", json={ + **automatic_body, field: value, + }, headers=first_headers) + assert rejected.status_code == 422 + assert service.cloud_specs == [] + + first_created = first.post("/api/v1/vms", json=automatic_body, + headers=first_headers) + second_created = second.post("/api/v1/vms", json={ + **automatic_body, "name": "tenant-two-cloud", + }, headers=second_headers) + assert first_created.status_code == second_created.status_code == 201 + first_ip = service.cloud_specs[0][0]["public_ip_cidr"] + second_ip = service.cloud_specs[1][0]["public_ip_cidr"] + for ip_cidr in (first_ip, second_ip): + interface = ipaddress.ip_interface(ip_cidr) + assert interface.network == network + assert str(interface.ip) not in excluded + assert first_ip != second_ip + for spec, _volume in service.cloud_specs: + assert spec["gateway"] == "8.8.8.1" + assert spec["dns_servers"] == ["1.1.1.1", "8.8.4.4"] + first_id = first_created.json()["uuid"] + second_id = second_created.json()["uuid"] + assert first.get(f"/api/v1/vms/{second_id}").status_code == 404 + assert second.get(f"/api/v1/vms/{first_id}").status_code == 404 + + # Every usable address is occupied in libvirt metadata: no IP may + # be reused even after the allocator has exhausted the /24 pool. + for address in network.hosts(): + ip = str(address) + if ip not in excluded and ip not in {first_ip.split("/")[0], + second_ip.split("/")[0]}: + service.vms[f"used-{ip}"] = {"uuid": f"used-{ip}", + "public_ip_cidr": f"{ip}/24"} + exhausted = first.post("/api/v1/vms", json={ + **automatic_body, "name": "no-ip-left", + }, headers=first_headers) + assert exhausted.status_code == 409 + assert len(service.cloud_specs) == 2 + + first_claim = f"{pool_scope}.{first_ip.split('/')[0]}" + assert store.get("ip_claim", first_claim) is not None + deleted = first.delete(f"/api/v1/vms/{first_id}", headers=first_headers) + assert deleted.status_code == 200 + assert store.get("ip_claim", first_claim) is None + replacement = first.post("/api/v1/vms", json={ + **automatic_body, "name": "freed-ip-reused", + }, headers=first_headers) + assert replacement.status_code == 201 + assert service.cloud_specs[-1][0]["public_ip_cidr"] == first_ip + + # With exactly one free address, a clearly rolled-back libvirt + # failure must release the temporary claim for the next attempt. + del service.vms["used-8.8.8.250"] + free_claim = f"{pool_scope}.8.8.8.250" + original_create = service.create_cloud_vm + + def rolled_back(_spec, _volume): + raise VMError("模拟创建失败,回滚已完成", 502) + + monkeypatch.setattr(service, "create_cloud_vm", rolled_back) + failed = first.post("/api/v1/vms", json={ + **automatic_body, "name": "rolled-back-vm", + }, headers=first_headers) + assert failed.status_code == 502 + assert store.get("ip_claim", free_claim) is None + + # If libvirt reports incomplete rollback, conservatively retain + # the address claim even though this fake exposes no resulting VM. + def incomplete_rollback(_spec, _volume): + raise VMError("模拟回滚不完整,请人工检查", 502) + + monkeypatch.setattr(service, "create_cloud_vm", incomplete_rollback) + uncertain = first.post("/api/v1/vms", json={ + **automatic_body, "name": "uncertain-vm", + }, headers=first_headers) + assert uncertain.status_code == 502 + assert store.get("ip_claim", free_claim) is not None + monkeypatch.setattr(service, "create_cloud_vm", original_create) + still_exhausted = first.post("/api/v1/vms", json={ + **automatic_body, "name": "uncertain-ip-protected", + }, headers=first_headers) + assert still_exhausted.status_code == 409 + + +@pytest.mark.parametrize(("vm_prefix", "first_ip"), [ + (None, "123.123.123.114/28"), + (24, "123.123.123.114/24"), +]) +def test_provider_28_pool_allocates_only_inside_assigned_block( + monkeypatch, tmp_path, vm_prefix, first_ip, +): + store = MemoryStore() + service = _Service() + manager = _Manager() + manager.profile = { + **_Manager.profile, + "host": "123.123.123.113", + "public_pool_cidr": "123.123.123.112/28", + "public_gateway": "123.123.123.113", + "public_dns_servers": ["1.1.1.1"], + "public_reserved_ips": ["123.123.123.115"], + "public_vm_prefix": vm_prefix, + } + monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( + DatabasePanelState(directory, store, store.users), manager, + DatabaseTemplateStore(store), store, + )) + monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics) + settings = Settings( + data_dir=tmp_path / "data", + static_dir=Path(__file__).resolve().parents[1] / "static", + ) + app = app_module.create_app(settings, service_factory=lambda _profile: service) + token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip() + automatic_body = { + key: value for key, value in CLOUD_VM.items() + if key not in {"public_ip_cidr", "gateway", "dns_servers"} + } + automatic_body["guest_ssh_public_key"] = GUEST_PUBLIC_KEY + + with TestClient(app, base_url=ORIGIN) as admin: + assert admin.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "database-password", "setup_token": token, + }).status_code == 200 + initial = admin.post("/api/v1/setup/admin", json={ + "token": token, "username": "operator", "password": PASSWORD, + }) + assert initial.status_code == 200 + headers = {"X-CSRF-Token": initial.json()["csrf_token"]} + store.users.promote("operator") + DatabaseTemplateStore(store).add(template_scope(manager.profile), { + "id": "alma10-template", "name": "AlmaLinux 10", + "volume_name": "panel-template-alma10.qcow2", + }) + created = admin.post("/api/v1/vms", json=automatic_body, headers=headers) + assert created.status_code == 201 + assert service.cloud_specs[0][0]["public_ip_cidr"] == first_ip + assert service.cloud_specs[0][0]["gateway"] == "123.123.123.113" + + # Exhaust the small provider allocation; never spill into the /24. + for address in ipaddress.ip_network("123.123.123.112/28").hosts(): + ip = str(address) + if ip not in {"123.123.123.113", "123.123.123.114", "123.123.123.115"}: + service.vms[f"used-{ip}"] = {"uuid": f"used-{ip}", + "public_ip_cidr": f"{ip}/{vm_prefix or 28}"} + exhausted = admin.post("/api/v1/vms", json={ + **automatic_body, "name": "no-provider-ip-left", + }, headers=headers) + assert exhausted.status_code == 409 + assert len(service.cloud_specs) == 1 diff --git a/engine/tests/test_remote_host.py b/engine/tests/test_remote_host.py new file mode 100644 index 00000000..a4c7bb7e --- /dev/null +++ b/engine/tests/test_remote_host.py @@ -0,0 +1,561 @@ +"""SSH host configuration is pinned, private, and switched only after test.""" + +from __future__ import annotations + +import base64 +import hashlib +import itertools +import json +import shutil +import stat +import struct +import subprocess +from dataclasses import replace +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import pytest + +from virsh_panel.remote_host import ( + HostProfile, + RemoteHostError, + RemoteHostManager, +) +from virsh_panel.ssh_agent import SSHAgentError + + +def host_key(seed: bytes) -> str: + blob = ( + struct.pack("!I", len(b"ssh-ed25519")) + + b"ssh-ed25519" + + struct.pack("!I", 32) + + seed * 32 + ) + return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii") + + +PRIVATE_KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\nZmFrZQ==\n-----END OPENSSH PRIVATE KEY-----\n" + + +class Runner: + def __init__(self) -> None: + self.key = host_key(b"a") + self.ssh_exit = 0 + self.encrypted = False + self.public_key_type = "ssh-ed25519" + self.commands: list[list[str]] = [] + + def __call__(self, argv, **kwargs): + self.commands.append(argv) + assert kwargs["timeout"] <= 22 + assert kwargs["capture_output"] is True + assert kwargs["check"] is False + if argv[0] == "ssh-keyscan": + return subprocess.CompletedProcess(argv, 0, f"[host.example]:2222 {self.key}\n", "") + if argv[0] == "ssh-keygen": + if self.encrypted: + return subprocess.CompletedProcess(argv, 255, "", "passphrase required") + return subprocess.CompletedProcess(argv, 0, f"{self.public_key_type} fake-public-key\n", "") + if argv[0] == "ssh": + return subprocess.CompletedProcess(argv, self.ssh_exit, "", "permission denied") + raise AssertionError(argv) + + +def make_manager(tmp_path: Path, runner: Runner) -> RemoteHostManager: + return RemoteHostManager( + tmp_path / "service-home", + ssh_user_config_path=tmp_path / "service-home" / ".ssh" / "config", + runner=runner, + ) + + +def make_profile( + scanned: dict, *, key: str = PRIVATE_KEY, host: str = "host.example", + passphrase: str = "", storage_pool: str = "images", iso_pool: str = "iso", + rescue_iso_pool: str = "", default_network: str = "default", region: str = "", +) -> HostProfile: + return HostProfile( + host=host, + port=2222, + private_key=key, + host_key=scanned["known_hosts_line"], + private_key_passphrase=passphrase, + storage_pool=storage_pool, + iso_pool=iso_pool, + rescue_iso_pool=rescue_iso_pool, + default_network=default_network, + region=region, + ) + + +def test_region_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage(make_profile(scanned, region="中国香港"), scanned["fingerprint"]) + manager.test(staged) + assert manager.commit(staged)["region"] == "中国香港" + profile_path = staged.path / "profile.json" + legacy = json.loads(profile_path.read_text(encoding="utf-8")) + legacy.pop("region") + profile_path.write_text(json.dumps(legacy), encoding="utf-8") + assert manager.current()["region"] == "" + + +def test_public_pool_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + profile = replace( + make_profile(scanned), + public_pool_cidr="1.2.3.0/24", + public_gateway="1.2.3.1", + public_dns_servers=["1.1.1.1", "8.8.8.8"], + public_reserved_ips=["1.2.3.10", "1.2.3.10"], + ) + staged = manager.stage(profile, scanned["fingerprint"]) + assert staged.metadata["public_reserved_ips"] == ["1.2.3.10"] + manager.test(staged) + current = manager.commit(staged) + assert current["public_pool_cidr"] == "1.2.3.0/24" + assert current["public_gateway"] == "1.2.3.1" + assert current["public_dns_servers"] == ["1.1.1.1", "8.8.8.8"] + assert current["public_reserved_ips"] == ["1.2.3.10"] + metadata_path = staged.path / "profile.json" + legacy = json.loads(metadata_path.read_text(encoding="utf-8")) + for key in ("public_pool_cidr", "public_gateway", "public_dns_servers", "public_reserved_ips"): + legacy.pop(key) + metadata_path.write_text(json.dumps(legacy), encoding="utf-8") + assert manager.current()["public_pool_cidr"] == "" + assert manager.current()["public_dns_servers"] == [] + assert manager.current()["public_reserved_ips"] == [] + + +def test_provider_28_gateway_cidr_is_saved_as_canonical_network(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + profile = replace( + make_profile(scanned), + public_pool_cidr="123.123.123.113/28", + public_gateway="123.123.123.113", + public_dns_servers=["1.1.1.1"], + public_vm_prefix=24, + ) + staged = manager.stage(profile, scanned["fingerprint"]) + assert staged.metadata["public_pool_cidr"] == "123.123.123.112/28" + assert staged.metadata["public_vm_prefix"] == 24 + manager.test(staged) + assert manager.commit(staged)["public_pool_cidr"] == "123.123.123.112/28" + assert manager.current()["public_vm_prefix"] == 24 + + +class FakeAgent: + sequence = itertools.count() + + def __init__(self, generation: Path, _key_path: Path, passphrase: str) -> None: + if passphrase != "open-sesame": + raise SSHAgentError("bad passphrase") + self.socket_path = generation / f"agent-{next(self.sequence)}.sock" + self.public_key = host_key(b"b") + self.alive = True + + def close(self) -> None: + self.alive = False + + +def test_scan_returns_fingerprint_without_trusting_key(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + digest = hashlib.sha256(base64.b64decode(runner.key.split()[1])).digest() + assert scanned == { + "host": "host.example", + "port": 2222, + "key_type": "ssh-ed25519", + "fingerprint": "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("="), + "host_key": runner.key, + "known_hosts_line": "vp-managed " + runner.key, + } + assert manager.current() is None + assert not manager.ssh_user_config_path.exists() + assert runner.commands[0] == [ + "ssh-keyscan", "-T", "8", "-p", "2222", "-t", "ed25519", "host.example", + ] + + +def test_encrypted_key_is_memory_only_and_requires_unlock_after_restart(tmp_path): + runner = Runner() + runner.encrypted = True + data_dir = tmp_path / "panel-data" + manager = RemoteHostManager(data_dir, runner=runner, agent_factory=FakeAgent) + scanned = manager.scan("host.example", 2222) + staged = manager.stage( + make_profile(scanned, passphrase="open-sesame"), scanned["fingerprint"], + ) + config = (staged.path / "config").read_text(encoding="ascii") + assert f'IdentityFile "{staged.path / "identity.pub"}"' in config + assert f'IdentityAgent "{manager._agents[staged.path].socket_path}"' in config + assert all( + b"open-sesame" not in path.read_bytes() + for path in staged.path.iterdir() if path.is_file() + ) + manager.test(staged) + manager.commit(staged) + assert manager.current()["private_key_encrypted"] is True + assert manager.current()["key_locked"] is False + manager.close() + assert manager.current()["key_locked"] is True + + restarted = RemoteHostManager(data_dir, runner=runner, agent_factory=FakeAgent) + assert restarted.current()["key_locked"] is True + original_config = (staged.path / "config").read_text(encoding="ascii") + with pytest.raises(RemoteHostError, match="口令错误"): + restarted.unlock_current("wrong") + assert restarted.current()["key_locked"] is True + assert (staged.path / "config").read_text(encoding="ascii") == original_config + unlocked = restarted.unlock_current("open-sesame") + assert unlocked["key_locked"] is False + assert str(restarted._agents[staged.path].socket_path) in ( + staged.path / "config" + ).read_text(encoding="ascii") + restarted.close() + + +def test_encrypted_key_needs_passphrase_and_rejects_wrong_one(tmp_path): + runner = Runner() + runner.encrypted = True + manager = RemoteHostManager(tmp_path / "panel-data", runner=runner, agent_factory=FakeAgent) + scanned = manager.scan("host.example", 2222) + with pytest.raises(RemoteHostError, match="填写私钥口令"): + manager.stage(make_profile(scanned), scanned["fingerprint"]) + with pytest.raises(RemoteHostError, match="口令错误"): + manager.stage(make_profile(scanned, passphrase="wrong"), scanned["fingerprint"]) + assert not list((manager.data_dir / "generations").iterdir()) + + +def test_existing_host_directories_are_accepted_as_pool_selectors(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage( + make_profile(scanned, storage_pool="/home/kvm", iso_pool="/home/iso"), + scanned["fingerprint"], + ) + assert staged.metadata["storage_pool"] == "/home/kvm" + assert staged.metadata["iso_pool"] == "/home/iso" + manager.abort(staged) + + +def test_rescue_iso_pool_survives_host_save_and_legacy_defaults_unconfigured(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage( + make_profile(scanned, iso_pool="/home/iso", rescue_iso_pool="/home/rescue-iso"), + scanned["fingerprint"], + ) + assert staged.metadata["rescue_iso_pool"] == "/home/rescue-iso" + manager.test(staged) + assert manager.commit(staged)["rescue_iso_pool"] == "/home/rescue-iso" + profile_path = staged.path / "profile.json" + legacy = json.loads(profile_path.read_text(encoding="utf-8")) + legacy.pop("rescue_iso_pool") + profile_path.write_text(json.dumps(legacy), encoding="utf-8") + assert manager.current()["rescue_iso_pool"] == "" + + +@pytest.mark.parametrize( + "rescue_selector,iso_selector", + [ + ("iso", "iso"), + ("/home/iso", "/home/iso"), + ], +) +def test_rescue_pool_cannot_equal_install_iso_pool( + tmp_path, rescue_selector, iso_selector, +): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + with pytest.raises(RemoteHostError, match="不能与安装 ISO 池相同"): + manager.stage( + make_profile(scanned, iso_pool=iso_selector, rescue_iso_pool=rescue_selector), + scanned["fingerprint"], + ) + + +@pytest.mark.parametrize("selector", ["/", "/home/../iso", "/home//iso", "/home/iso/", None]) +def test_rejects_invalid_rescue_pool_selector(tmp_path, selector): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + with pytest.raises(RemoteHostError, match="救援 ISO 池"): + manager.stage( + make_profile(scanned, rescue_iso_pool=selector), + scanned["fingerprint"], + ) + + +def test_explicit_host_bridge_selector_is_accepted(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage( + make_profile(scanned, default_network="bridge:br0"), scanned["fingerprint"], + ) + assert staged.metadata["default_network"] == "bridge:br0" + manager.abort(staged) + + +@pytest.mark.parametrize( + "selector", ["bridge:", "bridge:br/0", "bridge:br 0", "bridge:-br0", + "bridge:" + "a" * 16], +) +def test_invalid_host_bridge_selector_is_rejected(tmp_path, selector): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + with pytest.raises(RemoteHostError, match="网桥名称格式无效"): + manager.stage(make_profile(scanned, default_network=selector), scanned["fingerprint"]) + + +def test_unencrypted_ecdsa_private_key_does_not_require_passphrase(tmp_path): + runner = Runner() + runner.public_key_type = "ecdsa-sha2-nistp256" + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage(make_profile(scanned), scanned["fingerprint"]) + assert staged.metadata["private_key_encrypted"] is False + assert "IdentityAgent none" in (staged.path / "config").read_text() + manager.abort(staged) + + +@pytest.mark.parametrize("bad_path", ["/", "/home/../kvm", "/home//kvm", "/home/kvm/"]) +def test_rejects_unsafe_pool_paths(tmp_path, bad_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + with pytest.raises(RemoteHostError, match="磁盘池"): + manager.stage(make_profile(scanned, storage_pool=bad_path), scanned["fingerprint"]) + + +def test_stage_test_commit_writes_private_pinned_ssh_config(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + stage = manager.stage(make_profile(scanned), scanned["fingerprint"]) + assert stage.tested is False + assert manager.current() is None + for name in ("id_private", "known_hosts", "config", "profile.json"): + path = stage.path / name + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert stat.S_IMODE(stage.path.stat().st_mode) == 0o700 + config = (stage.path / "config").read_text() + assert "Host vp-managed\n" in config + assert "HostName host.example\n" in config + assert "Port 2222\n" in config + assert "User root\n" in config + assert "HostKeyAlias vp-managed\n" in config + assert "StrictHostKeyChecking yes\n" in config + assert "BatchMode yes\n" in config + assert "IdentitiesOnly yes\n" in config + assert "PasswordAuthentication no\n" in config + assert "HostKeyAlgorithms ssh-ed25519\n" in config + assert "ServerAliveInterval 15\n" in config + assert "ServerAliveCountMax 2\n" in config + assert (stage.path / "known_hosts").read_text() == scanned["known_hosts_line"] + "\n" + assert (stage.path / "id_private").read_text() == PRIVATE_KEY + wrapper = stage.path / "ssh-wrapper" + assert stat.S_IMODE(wrapper.stat().st_mode) == 0o700 + assert parse_qs(urlsplit(stage.libvirt_uri).query)["command"] == [str(wrapper)] + assert manager.test(stage) == {"ok": True, "ssh": "connected", "libvirt": "available"} + assert runner.commands[-1][0:4] == ["ssh", "-F", stage.ssh_config_file, "-T"] + current = manager.commit(stage) + assert current["host"] == "host.example" + assert current["port"] == 2222 + assert current["fingerprint"] == scanned["fingerprint"] + assert current["private_key_configured"] is True + assert current["libvirt_uri"].startswith( + "qemu+ssh://root@vp-managed/system?no_tty=1&command=" + ) + assert parse_qs(urlsplit(current["libvirt_uri"]).query)["command"] == [str(wrapper)] + assert manager.libvirt_uri == current["libvirt_uri"] + assert current["ssh_target"] == "vp-managed" + assert "private_key" not in current + assert PRIVATE_KEY not in repr(current) + assert manager.ssh_user_config_path.is_symlink() + assert manager.ssh_user_config_path.resolve() == stage.path / "config" + assert stat.S_IMODE(manager.ssh_user_config_path.parent.stat().st_mode) == 0o700 + + +def test_rejects_unconfirmed_or_changed_host_key(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + with pytest.raises(RemoteHostError, match="确认"): + manager.stage(make_profile(scanned), "") + runner.key = host_key(b"b") + with pytest.raises(RemoteHostError) as error: + manager.stage(make_profile(scanned), scanned["fingerprint"]) + assert error.value.status == 409 + assert manager.current() is None + + +def test_failed_test_preserves_old_connection_and_key_can_be_reused(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + first_scan = manager.scan("host.example", 2222) + first = manager.stage(make_profile(first_scan), first_scan["fingerprint"]) + manager.test(first) + manager.commit(first) + first_config = manager.ssh_user_config_path.resolve() + + next_scan = manager.scan("other.example", 2222) + second = manager.stage( + make_profile(next_scan, key="", host="other.example"), + next_scan["fingerprint"], + ) + assert (second.path / "id_private").read_text() == PRIVATE_KEY + runner.ssh_exit = 255 + with pytest.raises(RemoteHostError) as error: + manager.test(second) + assert error.value.status == 502 + with pytest.raises(RemoteHostError, match="测试"): + manager.commit(second) + assert manager.ssh_user_config_path.resolve() == first_config + assert manager.current()["host"] == "host.example" + manager.abort(second) + assert not second.path.exists() + + +def test_first_connection_needs_key_and_does_not_replace_existing_config(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + with pytest.raises(RemoteHostError, match="首次"): + manager.stage(make_profile(scanned, key=""), scanned["fingerprint"]) + manager.ssh_user_config_path.parent.mkdir(mode=0o700, parents=True) + manager.ssh_user_config_path.write_text("Host unrelated\n") + staged = manager.stage(make_profile(scanned), scanned["fingerprint"]) + manager.test(staged) + with pytest.raises(RemoteHostError, match="已有其他 SSH 配置"): + manager.commit(staged) + assert manager.ssh_user_config_path.read_text() == "Host unrelated\n" + assert manager.current() is None + + +@pytest.mark.skipif(shutil.which("ssh") is None, reason="OpenSSH client unavailable") +def test_openssh_reads_staged_nondefault_port_and_root_identity(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage(make_profile(scanned), scanned["fingerprint"]) + result = subprocess.run( + ["ssh", "-G", "-F", staged.ssh_config_file, "vp-managed"], + check=True, + capture_output=True, + text=True, + timeout=8, + ) + options = dict(line.split(" ", 1) for line in result.stdout.splitlines() if " " in line) + assert options["hostname"] == "host.example" + assert options["port"] == "2222" + assert options["user"] == "root" + assert options["hostkeyalias"] == "vp-managed" + assert options["stricthostkeychecking"] == "true" + assert options["identityfile"] == str(staged.path / "id_private") + assert options["userknownhostsfile"] == str(staged.path / "known_hosts") + + +def test_staged_wrapper_passes_config_to_ssh_without_shell(tmp_path): + runner = Runner() + manager = RemoteHostManager( + tmp_path / "service-home", ssh_binary="/bin/echo", runner=runner + ) + scanned = manager.scan("host.example", 2222) + staged = manager.stage(make_profile(scanned), scanned["fingerprint"]) + result = subprocess.run( + [str(staged.path / "ssh-wrapper"), "-T", "root@vp-managed"], + check=True, + capture_output=True, + text=True, + timeout=8, + ) + assert result.stdout.strip() == f"-F {staged.ssh_config_file} -T root@vp-managed" + + +def test_only_retired_generations_are_pruned(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + first = manager.stage(make_profile(scanned), scanned["fingerprint"]) + manager.test(first) + manager.commit(first) + second = manager.stage(make_profile(scanned, key=""), scanned["fingerprint"]) + # An uncommitted generation must not be deleted by background cleanup. + assert manager.cleanup_inactive(grace_seconds=0) == 0 + assert second.path.is_dir() + manager.test(second) + manager.commit(second) + assert manager.cleanup_inactive(grace_seconds=60) == 0 + assert first.path.is_dir() + assert manager.cleanup_inactive(grace_seconds=0) == 1 + assert not first.path.exists() + assert second.path.is_dir() + assert manager.current()["ssh_config_file"] == second.ssh_config_file + + +def test_symlinked_parent_keeps_active_generation(tmp_path): + # A lexical/canonical path mismatch must not classify the active + # generation as retired. + actual_parent = tmp_path / "private" / "virsh-panel" + actual_parent.mkdir(parents=True) + public_parent = tmp_path / "public-parent" + public_parent.symlink_to(actual_parent, target_is_directory=True) + runner = Runner() + manager = RemoteHostManager(public_parent / "state", runner=runner) + assert manager.data_dir == actual_parent / "state" + scanned = manager.scan("host.example", 2222) + first = manager.stage(make_profile(scanned), scanned["fingerprint"]) + manager.test(first) + manager.commit(first) + assert manager.current()["ssh_config_file"] == first.ssh_config_file + assert manager.cleanup_inactive(grace_seconds=0) == 0 + assert first.path.is_dir() + restarted = RemoteHostManager(public_parent / "state", runner=runner) + assert restarted.current()["ssh_config_file"] == first.ssh_config_file + assert restarted.cleanup_inactive(grace_seconds=0) == 0 + assert first.path.is_dir() + + second = restarted.stage(make_profile(scanned, key=""), scanned["fingerprint"]) + restarted.test(second) + restarted.commit(second) + assert restarted.cleanup_inactive(grace_seconds=0) == 1 + assert not first.path.exists() + assert second.path.is_dir() + assert restarted.current()["ssh_config_file"] == second.ssh_config_file + + +def test_rejects_symlink_as_final_data_directory(tmp_path): + actual = tmp_path / "actual" + actual.mkdir() + alias = tmp_path / "alias" + alias.symlink_to(actual, target_is_directory=True) + with pytest.raises(RemoteHostError, match="符号链接"): + RemoteHostManager(alias, runner=Runner()) + + +@pytest.mark.parametrize("host,port", [ + ("-oProxyCommand=bad", 22), + ("host.example\nUser attacker", 22), + ("example.com", 0), + ("example.com", 65536), + ("example.com", True), +]) +def test_rejects_host_and_port_injection(tmp_path, host, port): + runner = Runner() + manager = make_manager(tmp_path, runner) + with pytest.raises(RemoteHostError): + manager.scan(host, port) + assert runner.commands == [] diff --git a/engine/tests/test_rescue_templates.py b/engine/tests/test_rescue_templates.py new file mode 100644 index 00000000..93b62429 --- /dev/null +++ b/engine/tests/test_rescue_templates.py @@ -0,0 +1,71 @@ +"""Rescue ISO catalog and bootable-file boundary tests.""" + +from __future__ import annotations + +import pytest + +from virsh_panel.cloud_templates import TemplateError +from virsh_panel.rescue_templates import ( + RescueTemplateStore, rescue_scope, rescue_volume_name, verify_bootable_iso, +) + + +def _profile(rescue_iso_pool="rescue"): + return { + "host": "vmhost.example", "port": 2222, "fingerprint": "SHA256:vmhost", + "iso_pool": "iso", "rescue_iso_pool": rescue_iso_pool, + } + + +def _iso_bytes(bootable=True): + image = bytearray(1024 * 1024) + for sector, kind in ((16, 1), (17, 0 if bootable else 2), (18, 255)): + offset = sector * 2048 + image[offset] = kind + image[offset + 1:offset + 6] = b"CD001" + image[offset + 6] = 1 + if bootable: + image[17 * 2048 + 7:17 * 2048 + 30] = b"EL TORITO SPECIFICATION" + image[17 * 2048 + 71:17 * 2048 + 75] = (20).to_bytes(4, "little") + return bytes(image) + + +def test_rescue_catalog_is_scoped_to_rescue_pool_and_rejects_duplicate_names(): + catalog = RescueTemplateStore(None) + first_scope = rescue_scope(_profile()) + second_scope = rescue_scope(_profile("other-rescue")) + assert first_scope != second_scope + template_id = "a" * 32 + record = { + "id": template_id, "name": "System Rescue", + "volume_name": rescue_volume_name(template_id), + "size_bytes": 1024 * 1024, "sha256": "b" * 64, + } + catalog.add(first_scope, record) + assert catalog.list(second_scope) == [] + assert catalog.get(first_scope, template_id)["name"] == "System Rescue" + with pytest.raises(TemplateError): + catalog.add(first_scope, {**record, "id": "c" * 32, + "volume_name": rescue_volume_name("c" * 32)}) + catalog.delete(first_scope, template_id) + assert catalog.list(first_scope) == [] + + +def test_rescue_catalog_requires_separate_configured_pool(): + with pytest.raises(TemplateError, match="救援 ISO 目录"): + rescue_scope(_profile("")) + assert rescue_scope(_profile()) == rescue_scope({ + **_profile(), "iso_pool": "other-install-iso", + }) + + +def test_rescue_iso_must_include_el_torito_boot_record(tmp_path): + path = tmp_path / "rescue.iso" + path.write_bytes(_iso_bytes()) + verify_bootable_iso(path) + path.write_bytes(_iso_bytes(bootable=False)) + with pytest.raises(TemplateError, match="El Torito"): + verify_bootable_iso(path) + path.write_bytes(b"not an ISO") + with pytest.raises(TemplateError): + verify_bootable_iso(path) diff --git a/engine/tests/test_smtp_service.py b/engine/tests/test_smtp_service.py new file mode 100644 index 00000000..d2906a3c --- /dev/null +++ b/engine/tests/test_smtp_service.py @@ -0,0 +1,201 @@ +"""SMTP settings safety and registration mail transport tests.""" + +from __future__ import annotations + +import smtplib + +import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from virsh_panel.database import DatabaseStore +from virsh_panel.smtp_service import ( + SMTPConfig, SMTPError, SMTPSettingsStore, send_verification_code, validate_email, +) + + +def _settings(**overrides): + values = { + "host": "smtp.example.com", "port": 587, "tls_mode": "starttls", + "from_address": "no-reply@example.com", "username": "account@example.com", + "password": "app-password-secret", + } + values.update(overrides) + return values + + +class EncryptedRecords: + def __init__(self): + self.cipher = DatabaseStore.__new__(DatabaseStore) + self.cipher._cipher = AESGCM(b"s" * 32) + self.data = {} + + def get(self, kind, key): + encrypted = self.data.get((kind, key)) + return None if encrypted is None else self.cipher._decrypt(kind, key, encrypted) + + def set(self, kind, key, value): + self.data[(kind, key)] = self.cipher._encrypt(kind, key, value) + + +def test_smtp_settings_are_encrypted_and_password_never_returns_in_status(): + records = EncryptedRecords() + settings = SMTPSettingsStore(records) + assert settings.public_status() == {"configured": False} + + config = settings.save(_settings()) + assert config.password == "app-password-secret" + ciphertext = records.data[("smtp", "current")] + assert b"app-password-secret" not in ciphertext + assert b"smtp.example.com" not in ciphertext + + status = settings.public_status() + assert status == { + "configured": True, "host": "smtp.example.com", "port": 587, + "tls_mode": "starttls", "from_address": "no-reply@example.com", + "username": "account@example.com", "password_configured": True, + } + assert "app-password-secret" not in repr(config) + assert "password" not in status + + +def test_smtp_update_keeps_existing_password_only_for_same_account(): + settings = SMTPSettingsStore(EncryptedRecords()) + settings.save(_settings()) + assert settings.save(_settings(host="new.example.com", password="")).password == "app-password-secret" + with pytest.raises(SMTPError, match="必须同时填写"): + settings.save(_settings(username="other@example.com", password="")) + assert settings.get().host == "new.example.com" + assert settings.get().username == "account@example.com" + + +@pytest.mark.parametrize("value", [ + _settings(host="smtp.example.com\r\nX-Injected: yes"), + _settings(port=True), + _settings(port=0), + _settings(tls_mode="invalid"), + _settings(tls_mode=[]), + _settings(from_address="Sender "), + _settings(username="x", password="", tls_mode="starttls"), + _settings(tls_mode="none"), +]) +def test_invalid_smtp_settings_are_rejected(value): + with pytest.raises(SMTPError): + SMTPConfig.from_mapping(value) + + +@pytest.mark.parametrize("address", [ + "user@example.com\r\nBcc: victim@example.com", "Name ", + "user..name@example.com", "user@", "@example.com", " user@example.com", +]) +def test_invalid_mailbox_is_rejected(address): + with pytest.raises(SMTPError, match="邮箱地址格式无效"): + validate_email(address) + + +def test_address_keeps_local_part_and_canonicalizes_domain(): + assert validate_email("User+tag@EXAMPLE.COM") == "User+tag@example.com" + + +class FakeSMTP: + events = [] + sent = None + refused = {} + + def __init__(self, host, port, **kwargs): + self.events.append(("connect", host, port, kwargs)) + + def __enter__(self): + return self + + def __exit__(self, *_args): + self.events.append("quit") + + def ehlo(self): + self.events.append("ehlo") + + def starttls(self, **kwargs): + assert "context" in kwargs + self.events.append("starttls") + + def login(self, username, password): + self.events.append(("login", username, password)) + + def send_message(self, message): + self.events.append("send") + self.sent = message + return self.refused + + +def test_starttls_happens_before_login_and_sends_six_digit_code(monkeypatch): + FakeSMTP.events = [] + FakeSMTP.refused = {} + instances = [] + + def make_client(*args, **kwargs): + client = FakeSMTP(*args, **kwargs) + instances.append(client) + return client + + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", make_client) + send_verification_code(SMTPConfig.from_mapping(_settings()), "user@example.com", "012345") + + assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 587) + assert FakeSMTP.events[0][3]["timeout"] == 10 + assert FakeSMTP.events[1:] == [ + "ehlo", "starttls", "ehlo", + ("login", "account@example.com", "app-password-secret"), "send", "quit", + ] + message = instances[0].sent + assert message["To"] == "user@example.com" + assert message["From"] == "no-reply@example.com" + assert "012345" in message.get_content() + + +def test_ssl_and_unauthenticated_local_relay(monkeypatch): + FakeSMTP.events = [] + FakeSMTP.refused = {} + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP_SSL", FakeSMTP) + send_verification_code( + SMTPConfig.from_mapping(_settings(port=465, tls_mode="ssl")), + "user@example.com", "123456", + ) + assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 465) + assert "context" in FakeSMTP.events[0][3] + assert "starttls" not in FakeSMTP.events + + FakeSMTP.events = [] + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP) + send_verification_code( + SMTPConfig.from_mapping(_settings(port=25, tls_mode="none", username="", password="")), + "user@example.com", "123456", + ) + assert not any(isinstance(event, tuple) and event[0] == "login" + for event in FakeSMTP.events) + + +def test_smtp_transport_failure_is_redacted(monkeypatch): + class FailingSMTP(FakeSMTP): + def login(self, *_args): + raise smtplib.SMTPAuthenticationError(535, b"secret server reply") + + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FailingSMTP) + with pytest.raises(SMTPError) as failure: + send_verification_code( + SMTPConfig.from_mapping(_settings()), "user@example.com", "123456", + ) + assert failure.value.status == 502 + assert "secret" not in str(failure.value) + assert "app-password" not in str(failure.value) + + +def test_refused_recipient_and_bad_code_do_not_leak_details(monkeypatch): + FakeSMTP.events = [] + FakeSMTP.refused = {"user@example.com": (550, "mailbox secret")} + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP) + config = SMTPConfig.from_mapping(_settings()) + with pytest.raises(SMTPError) as failure: + send_verification_code(config, "user@example.com", "123456") + assert failure.value.status == 502 + assert "secret" not in str(failure.value) + with pytest.raises(SMTPError, match="验证码格式无效"): + send_verification_code(config, "user@example.com", "00000\n") diff --git a/engine/tests/test_ssh_agent.py b/engine/tests/test_ssh_agent.py new file mode 100644 index 00000000..fd61f655 --- /dev/null +++ b/engine/tests/test_ssh_agent.py @@ -0,0 +1,210 @@ +"""Exercise passphrase loading without a remote SSH server.""" + +from __future__ import annotations + +import errno +import os +import select +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +import pytest + +from virsh_panel.ssh_agent import SSHAgentError, SSHAgentSession + + +@pytest.fixture +def encrypted_key() -> tuple[Path, Path, str]: + for command in ("ssh-agent", "ssh-add", "ssh-keygen"): + if shutil.which(command) is None: + pytest.skip(f"{command} is unavailable") + temporary_root = "/private/tmp" if Path("/private/tmp").is_dir() else "/tmp" + with tempfile.TemporaryDirectory(prefix="vp-agent-", dir=temporary_root) as directory: + generation = Path(directory) / "generation" + generation.mkdir(mode=0o700) + probe_path = generation / "probe.sock" + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe: + try: + probe.bind(str(probe_path)) + except OSError as exc: + if sys.platform == "darwin" and exc.errno in {errno.EACCES, errno.EPERM}: + pytest.skip("test environment forbids local Unix sockets") + raise + probe_path.unlink() + key_path = generation / "id_private" + passphrase = "integration-test-only-phrase" + subprocess.run( + ["ssh-keygen", "-q", "-t", "ed25519", "-N", passphrase, "-f", str(key_path)], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + check=True, + timeout=10, + ) + yield generation, key_path, passphrase + + +def test_load_encrypted_key_and_close(encrypted_key: tuple[Path, Path, str]) -> None: + generation, key_path, passphrase = encrypted_key + session = SSHAgentSession(generation, key_path, passphrase) + socket_path = session.socket_path + try: + assert socket_path.parent == generation + assert socket_path.is_socket() + assert session.alive + assert session.public_key.startswith("ssh-ed25519 ") + assert not list(generation.glob("askpass-*")) + listed = subprocess.run( + ["ssh-add", "-L"], + env={**os.environ, "SSH_AUTH_SOCK": str(socket_path)}, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + check=True, + timeout=5, + ) + assert listed.stdout.startswith(session.public_key) + finally: + session.close() + assert not session.alive + assert not socket_path.exists() + + +def test_wrong_passphrase_cleans_up(encrypted_key: tuple[Path, Path, str]) -> None: + generation, key_path, _passphrase = encrypted_key + with pytest.raises(SSHAgentError, match="无法解锁"): + SSHAgentSession(generation, key_path, "incorrect-test-only-phrase") + assert not list(generation.glob("agent-*.sock")) + assert not list(generation.glob("askpass-*")) + + +def test_two_sessions_do_not_share_socket(encrypted_key: tuple[Path, Path, str]) -> None: + generation, key_path, passphrase = encrypted_key + first = SSHAgentSession(generation, key_path, passphrase) + second = SSHAgentSession(generation, key_path, passphrase) + try: + assert first.socket_path != second.socket_path + first.close() + assert second.alive + finally: + first.close() + second.close() + + +@pytest.mark.parametrize("bad", ["x\ny", "x\ry", "x\x00y", "x" * 1024]) +def test_rejects_unsafe_passphrase( + encrypted_key: tuple[Path, Path, str], bad: str +) -> None: + generation, key_path, _passphrase = encrypted_key + with pytest.raises(SSHAgentError): + SSHAgentSession(generation, key_path, bad) + assert not list(generation.glob("agent-*.sock")) + + +def test_passphrase_is_not_in_arguments_or_environment( + encrypted_key: tuple[Path, Path, str], monkeypatch: pytest.MonkeyPatch +) -> None: + generation, key_path, passphrase = encrypted_key + original_run = subprocess.run + observed: list[dict[str, object]] = [] + + def checking_run(argv: list[str], **kwargs: object) -> subprocess.CompletedProcess[object]: + if Path(argv[0]).name == "ssh-add" and "-q" in argv: + observed.append(kwargs) + assert passphrase not in repr(argv) + assert passphrase not in repr(kwargs.get("env")) + assert kwargs.get("pass_fds") + assert kwargs.get("stdin") == subprocess.DEVNULL + return original_run(argv, **kwargs) + + monkeypatch.setattr(subprocess, "run", checking_run) + session = SSHAgentSession(generation, key_path, passphrase) + try: + assert session.alive + assert len(observed) == 1 + finally: + session.close() + + +@pytest.mark.skipif(sys.platform != "linux", reason="Linux parent-death watchdog") +def test_linux_agent_survives_creator_thread_exit( + encrypted_key: tuple[Path, Path, str] +) -> None: + generation, key_path, passphrase = encrypted_key + created: dict[str, object] = {} + + def create() -> None: + try: + created["session"] = SSHAgentSession(generation, key_path, passphrase) + except Exception as exc: + created["error"] = exc + + thread = threading.Thread(target=create) + thread.start() + thread.join(timeout=20) + assert not thread.is_alive() + error = created.get("error") + if isinstance(error, BaseException): + raise error + session = created["session"] + assert isinstance(session, SSHAgentSession) + try: + # Direct PR_SET_PDEATHSIG on the app-spawned agent would kill it when + # this worker thread exits, even though the panel process is alive. + time.sleep(0.2) + assert session.alive + finally: + session.close() + + +@pytest.mark.skipif(sys.platform != "linux", reason="Linux parent-death watchdog") +def test_linux_agent_ends_after_panel_sigkill( + encrypted_key: tuple[Path, Path, str] +) -> None: + generation, key_path, passphrase = encrypted_key + child_code = ( + "import sys,time\n" + "from pathlib import Path\n" + "from virsh_panel.ssh_agent import SSHAgentSession\n" + "session=SSHAgentSession(Path(sys.argv[1]),Path(sys.argv[2])," + "sys.stdin.readline().rstrip('\\n'))\n" + "print(session.socket_path, flush=True)\n" + "time.sleep(60)\n" + ) + panel = subprocess.Popen( + [sys.executable, "-c", child_code, str(generation), str(key_path)], + cwd=str(Path(__file__).resolve().parents[1]), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + try: + assert panel.stdin is not None + panel.stdin.write(passphrase + "\n") + panel.stdin.close() + assert panel.stdout is not None + readable, _, _ = select.select([panel.stdout], [], [], 15) + assert readable, "panel subprocess did not report its agent socket" + socket_name = panel.stdout.readline().strip() + assert socket_name, "panel subprocess exited before starting its agent" + agent_socket = Path(socket_name) + assert agent_socket.is_socket() + + os.kill(panel.pid, signal.SIGKILL) + panel.wait(timeout=5) + deadline = time.monotonic() + 5 + while agent_socket.exists() and time.monotonic() < deadline: + time.sleep(0.05) + assert not agent_socket.exists(), "agent socket survived the panel process" + finally: + if panel.poll() is None: + panel.kill() + panel.wait(timeout=5) diff --git a/engine/tests/test_ssh_keys.py b/engine/tests/test_ssh_keys.py new file mode 100644 index 00000000..3d2b1f73 --- /dev/null +++ b/engine/tests/test_ssh_keys.py @@ -0,0 +1,168 @@ +"""Owner-isolated MariaDB SSH public key records, using a SQL test adapter.""" + +from __future__ import annotations + +import base64 +import hashlib +import sqlite3 +import struct + +import pytest + +from virsh_panel.ssh_keys import DatabaseSSHKeyStore, SSHKeyError + + +def _valid_key(seed: bytes = b"a", comment: str = "operator@example") -> str: + blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + seed * 32 + return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii") + " " + comment + + +class _Cursor: + def __init__(self, connection: sqlite3.Connection) -> None: + self._cursor = connection.cursor() + + def __enter__(self): + return self + + def __exit__(self, *_exc): + self._cursor.close() + + def execute(self, statement, parameters=()): + try: + self._cursor.execute(statement.replace("%s", "?"), parameters) + except sqlite3.IntegrityError as exc: + import pymysql + + raise pymysql.err.IntegrityError(1062, str(exc)) from exc + return self + + def fetchone(self): + row = self._cursor.fetchone() + return None if row is None else dict(row) + + def fetchall(self): + return [dict(row) for row in self._cursor.fetchall()] + + @property + def lastrowid(self): + return self._cursor.lastrowid + + @property + def rowcount(self): + return self._cursor.rowcount + + +class _Connection: + def __init__(self) -> None: + self.raw = sqlite3.connect(":memory:") + self.raw.row_factory = sqlite3.Row + self.raw.execute("PRAGMA foreign_keys=ON") + self.raw.executescript(""" + CREATE TABLE users (id INTEGER PRIMARY KEY); + INSERT INTO users (id) VALUES (1), (2); + CREATE TABLE user_ssh_keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + public_key TEXT NOT NULL, + fingerprint TEXT NOT NULL, + created_at INTEGER NOT NULL, + UNIQUE (user_id, fingerprint) + ); + """) + + def cursor(self): + return _Cursor(self.raw) + + def commit(self): + self.raw.commit() + + def rollback(self): + self.raw.rollback() + + def close(self): + # A single in-memory database must outlive individual store calls. + pass + + +class _Store: + def __init__(self) -> None: + self.connection = _Connection() + + def _connect(self): + return self.connection + + +@pytest.fixture +def key_store(): + store = _Store() + yield DatabaseSSHKeyStore(store), store.connection.raw + store.connection.raw.close() + + +def test_keys_are_strictly_isolated_by_user_on_all_operations(key_store): + repository, database = key_store + first = repository.create_for_user(1, "生产环境", _valid_key(), now=100) + second = repository.create_for_user(2, "另一用户", _valid_key(), now=101) + assert first["id"] != second["id"] + assert first["fingerprint"] == second["fingerprint"] + assert first["public_key"] == _valid_key().rsplit(" ", 1)[0] + blob = base64.b64decode(first["public_key"].split()[1]) + assert first["fingerprint"] == ( + "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=") + ) + assert repository.list_for_user(1) == [first] + assert repository.list_for_user(2) == [second] + assert repository.get_for_user(1, second["id"]) is None + assert repository.get_for_user(2, first["id"]) is None + assert repository.delete_for_user(2, first["id"]) is False + assert repository.get_for_user(1, first["id"]) == first + assert repository.delete_for_user(1, first["id"]) is True + assert repository.delete_for_user(1, first["id"]) is False + assert repository.list_for_user(1) == [] + assert repository.list_for_user(2) == [second] + database.execute("DELETE FROM users WHERE id=2") + database.commit() + assert database.execute("SELECT COUNT(*) FROM user_ssh_keys").fetchone()[0] == 0 + + +def test_same_wire_key_cannot_be_saved_twice_per_user_even_with_new_comment(key_store): + repository, _database = key_store + repository.create_for_user(1, "第一把", _valid_key(comment="first")) + with pytest.raises(SSHKeyError) as duplicate: + repository.create_for_user(1, "第二把", _valid_key(comment="second")) + assert duplicate.value.status == 409 + assert len(repository.list_for_user(1)) == 1 + # Unique constraint is owner-scoped, not a global ban on shared keys. + assert repository.create_for_user(2, "允许跨用户重复", _valid_key(comment="second"))["id"] > 0 + + +@pytest.mark.parametrize("invalid_key", [ + "-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----", + "ssh-ed25519 not-base64", + "ssh-rsa " + _valid_key().split()[1], + _valid_key() + "\nssh-ed25519 another-key", + "", +]) +def test_private_or_invalid_public_keys_are_rejected_without_writes(key_store, invalid_key): + repository, _database = key_store + with pytest.raises(SSHKeyError) as invalid: + repository.create_for_user(1, "键", invalid_key) + assert invalid.value.status == 400 + assert repository.list_for_user(1) == [] + + +@pytest.mark.parametrize("invalid_name", ["", " ", " leading", "trailing ", "bad\nname", "x" * 81]) +def test_key_name_must_be_safe_and_bounded(key_store, invalid_name): + repository, _database = key_store + with pytest.raises(SSHKeyError): + repository.create_for_user(1, invalid_name, _valid_key()) + assert repository.list_for_user(1) == [] + + +def test_list_is_newest_first_and_exposes_no_owner_id(key_store): + repository, _database = key_store + first = repository.create_for_user(1, "first", _valid_key(b"a"), now=100) + second = repository.create_for_user(1, "second", _valid_key(b"b"), now=200) + assert repository.list_for_user(1) == [second, first] + assert "user_id" not in second diff --git a/engine/tests/test_template_frontend.py b/engine/tests/test_template_frontend.py new file mode 100644 index 00000000..ee086571 --- /dev/null +++ b/engine/tests/test_template_frontend.py @@ -0,0 +1,218 @@ +"""Guard the administrator-only image catalog and card-based VM image picker.""" + +from __future__ import annotations + +from dataclasses import dataclass +from html.parser import HTMLParser +from pathlib import Path +import re +from xml.etree import ElementTree + +import pytest + + +STATIC = Path(__file__).resolve().parents[1] / "static" +VOID_TAGS = { + "area", "base", "br", "col", "embed", "hr", "img", "input", + "link", "meta", "param", "source", "track", "wbr", +} + + +@dataclass(frozen=True) +class Element: + tag: str + attrs: dict[str, str | None] + ancestor_ids: tuple[str, ...] + + +class CatalogPageParser(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.elements: list[Element] = [] + self.stack: list[Element] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + element = Element( + tag, + dict(attrs), + tuple(item.attrs["id"] for item in self.stack if item.attrs.get("id")), + ) + self.elements.append(element) + if tag not in VOID_TAGS: + self.stack.append(element) + + def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + self.handle_starttag(tag, attrs) + if tag not in VOID_TAGS: + self.stack.pop() + + def handle_endtag(self, tag: str) -> None: + for index in range(len(self.stack) - 1, -1, -1): + if self.stack[index].tag == tag: + del self.stack[index:] + return + + +@pytest.fixture(scope="module") +def page() -> tuple[list[Element], dict[str, Element]]: + parser = CatalogPageParser() + parser.feed((STATIC / "index.html").read_text(encoding="utf-8")) + assert not parser.stack, "Unclosed HTML element in the dashboard page" + by_id = {element.attrs["id"]: element for element in parser.elements if element.attrs.get("id")} + assert len(by_id) == sum(bool(element.attrs.get("id")) for element in parser.elements) + return parser.elements, by_id + + +def test_image_import_is_on_a_dedicated_admin_page(page) -> None: + _, by_id = page + workspace = by_id["template-workspace"] + assert "hidden" in workspace.attrs + assert "dashboard-view" in workspace.ancestor_ids + + form = by_id["template-import-form"] + assert form.tag == "form" + assert "template-workspace" in form.ancestor_ids + for element_id in ("template-name", "template-url", "template-sha256", "template-import-button"): + assert "template-import-form" in by_id[element_id].ancestor_ids + assert "create-view" not in by_id[element_id].ancestor_ids + assert "reinstall-view" not in by_id[element_id].ancestor_ids + + assert "template-workspace" in by_id["template-admin-list"].ancestor_ids + assert "template-import" not in by_id, "The old inline import details must be removed" + + +@pytest.mark.parametrize( + ("form_id", "field_id", "catalog_id"), + [ + ("create-form", "vm-template", "vm-template-catalog"), + ("reinstall-form", "reinstall-template", "reinstall-template-catalog"), + ], +) +def test_vm_image_selection_uses_cards_not_selects( + page, form_id: str, field_id: str, catalog_id: str +) -> None: + elements, by_id = page + field = by_id[field_id] + catalog = by_id[catalog_id] + assert field.tag == "input" + assert field.attrs.get("type") == "hidden" + assert field.attrs.get("name") == "template_id" + assert form_id in field.ancestor_ids + assert catalog.tag == "div" + assert "template-catalog" in (catalog.attrs.get("class") or "").split() + assert form_id in catalog.ancestor_ids + assert not any( + element.tag == "select" + and element.attrs.get("name") == "template_id" + and form_id in element.ancestor_ids + for element in elements + ) + + +def test_catalog_renders_expandable_family_and_version_cards() -> None: + script = (STATIC / "app.js").read_text(encoding="utf-8") + assert 'makeElement("details", "template-family-card")' in script + assert 'makeElement("button", "template-version-option")' in script + assert 'option.dataset.templateId = id;' in script + assert 'option.setAttribute("aria-pressed"' in script + assert 'input.value = id;' in script + + +@pytest.mark.parametrize( + ("family", "filename"), + [ + ("AlmaLinux", "almalinux-icon.svg"), + ("Debian", "debian-icon.svg"), + ("CentOS", "centos-icon.svg"), + ("Ubuntu", "ubuntu-icon.svg"), + ], +) +def test_system_cards_use_bundled_vector_logos(family: str, filename: str) -> None: + script = (STATIC / "app.js").read_text(encoding="utf-8") + logo = STATIC / filename + assert logo.is_file() + artwork = logo.read_text(encoding="utf-8") + root = ElementTree.fromstring(artwork) + assert root.tag == "{http://www.w3.org/2000/svg}svg" + assert any(element.tag.endswith("}path") for element in root.iter()) + assert f'{family}: "/static/{filename}"' in script + + icon_code = script.split("function templateIcon(family, className) {", 1)[1].split( + "function renderTemplateCatalog(inputId) {", 1 + )[0] + assert "TEMPLATE_ICON_PATHS[family]" in icon_code + assert 'makeElement("img", "template-system-logo")' in icon_code + assert "logo.src = logoPath;" in icon_code + assert 'icon.append(logo);' in icon_code + assert 'icon.textContent = "A"' not in icon_code + + catalog_code = script.split("function renderTemplateCatalog(inputId) {", 1)[1].split( + "function renderTemplateAdminList() {", 1 + )[0] + admin_code = script.split("function renderTemplateAdminList() {", 1)[1].split( + "function fillTemplateViews", 1 + )[0] + assert 'templateIcon(family, "template-family-icon")' in catalog_code + assert 'templateIcon(family, "template-admin-icon")' in admin_code + + +def test_system_family_metadata_recognizes_debian_centos_and_ubuntu() -> None: + script = (STATIC / "app.js").read_text(encoding="utf-8") + names = script.split("const TEMPLATE_FAMILY_NAMES = {", 1)[1].split("};", 1)[0] + for metadata, family in ( + ("debian", "Debian"), + ("centos", "CentOS"), + ("centosstream", "CentOS"), + ("ubuntu", "Ubuntu"), + ): + assert f'{metadata}: "{family}"' in names + system_code = script.split("function templateSystem(item) {", 1)[1].split( + "function templateIcon(family, className) {", 1 + )[0] + assert "item?.os_family" in system_code + assert "TEMPLATE_FAMILY_NAMES[familyKey]" in system_code + + +def test_version_cards_show_only_centered_template_name() -> None: + script = (STATIC / "app.js").read_text(encoding="utf-8") + catalog_code = script.split("function renderTemplateCatalog(inputId) {", 1)[1].split( + "function renderTemplateAdminList() {", 1 + )[0] + option_code = catalog_code.split('const name = String(item.name || id);', 1)[1].split( + 'option.addEventListener("click"', 1 + )[0] + visible_lines = [ + line for line in option_code.splitlines() + if "option.append(" in line or "option.textContent" in line + ] + assert len(visible_lines) == 1 + assert 'makeElement("strong", "", name)' in visible_lines[0] + assert "versionLabel" not in visible_lines[0] + assert 'makeElement("small"' not in visible_lines[0] + + styles = (STATIC / "styles.css").read_text(encoding="utf-8") + version_rules = re.findall(r"\.template-version-option\{([^}]*)\}", styles) + text_align = [ + match.group(1) + for rule in version_rules + for match in re.finditer(r"text-align:([^;}]*)", rule) + ] + assert text_align[-1] == "center" + + +def test_admin_only_catalog_navigation_and_rename_control() -> None: + script = (STATIC / "app.js").read_text(encoding="utf-8") + session_code = script.split("function applySession(session) {", 1)[1].split( + "async function continueAfterLogin", 1 + )[0] + for element_id in ("template-settings-button", "template-settings-mobile-button"): + assert f'"{element_id}"' in session_code + assert 'byId(id).hidden = !state.admin;' in session_code + + rename_code = script.split("function renderTemplateAdminList() {", 1)[1].split( + "function fillTemplateViews", 1 + )[0] + assert 'makeElement("form", "template-admin-row")' in rename_code + assert 'name.type = "text";' in rename_code + assert 'method: "PATCH"' in rename_code + assert 'encodeURIComponent(id)' in rename_code diff --git a/engine/tests/test_update_worker.py b/engine/tests/test_update_worker.py new file mode 100644 index 00000000..bbd39de2 --- /dev/null +++ b/engine/tests/test_update_worker.py @@ -0,0 +1,80 @@ +"""The systemd post-stop hook must resolve interrupted update jobs.""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from unittest.mock import patch + +from virsh_panel import update_worker + + +class FakeStore: + def __init__(self, job_id: str | None): + self.job_id = job_id + + def get_value(self, name: str) -> str | None: + if name == "update.active_job": + return self.job_id + raise AssertionError(name) + + +class FakeUpdater: + def __init__(self, job: dict | None): + self.job = job + self.failed: list[tuple[str, str]] = [] + + def get_job(self, _job_id: str) -> dict | None: + return self.job + + def fail_job(self, job_id: str, message: str) -> None: + self.failed.append((job_id, message)) + if self.job is not None: + self.job["status"] = "failed" + + +class FinalizeIncompleteTests(unittest.TestCase): + def test_running_job_is_marked_failed_once(self): + store = FakeStore("job-1234567890123456") + updater = FakeUpdater({"status": "running"}) + self.assertTrue(update_worker.finalize_incomplete_job(updater, store)) + self.assertEqual(updater.job["status"], "failed") + self.assertEqual(len(updater.failed), 1) + self.assertIn("日志", updater.failed[0][1]) + self.assertFalse(update_worker.finalize_incomplete_job(updater, store)) + self.assertEqual(len(updater.failed), 1) + + def test_queued_job_is_marked_failed(self): + store = FakeStore("job-1234567890123456") + updater = FakeUpdater({"status": "queued"}) + self.assertTrue(update_worker.finalize_incomplete_job(updater, store)) + self.assertEqual(updater.job["status"], "failed") + + def test_terminal_or_missing_job_is_not_modified(self): + for status in ("succeeded", "failed"): + with self.subTest(status=status): + updater = FakeUpdater({"status": status}) + self.assertFalse(update_worker.finalize_incomplete_job( + updater, FakeStore("job-1234567890123456"))) + self.assertEqual(updater.failed, []) + self.assertFalse(update_worker.finalize_incomplete_job( + FakeUpdater(None), FakeStore("job-1234567890123456"))) + self.assertFalse(update_worker.finalize_incomplete_job( + FakeUpdater({"status": "running"}), FakeStore(None))) + + def test_cli_finalize_mode_does_not_run_update(self): + store = FakeStore("job-1234567890123456") + updater = FakeUpdater({"status": "running"}) + with patch.object(update_worker, "_load_updater", return_value=(updater, store)): + self.assertEqual(update_worker.main(["--finalize-incomplete"]), 0) + self.assertEqual(updater.job["status"], "failed") + + def test_private_engine_does_not_enable_legacy_update_service(self): + unit = (Path(__file__).resolve().parents[2] / "deploy" / + "virt-cloud-engine.service").read_text(encoding="utf-8") + self.assertIn("virsh_panel.internal:create_engine", unit) + self.assertNotIn("update_worker", unit) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/tests/test_updater.py b/engine/tests/test_updater.py new file mode 100644 index 00000000..bfe3236e --- /dev/null +++ b/engine/tests/test_updater.py @@ -0,0 +1,255 @@ +"""Offline checks for the private-repository update safety boundary.""" + +from __future__ import annotations + +import subprocess +import tempfile +import unittest +from pathlib import Path + +from virsh_panel.updater import REPOSITORY_URL, UpdateError, Updater + + +class MemoryStore: + def __init__(self): + self.secrets: dict[str, str] = {} + self.values: dict[str, str] = {} + + def get_secret(self, name): + return self.secrets.get(name) + + def set_secret(self, name, value): + self.secrets[name] = value + + def delete_secret(self, name): + self.secrets.pop(name, None) + + def get_value(self, name): + return self.values.get(name) + + def set_value(self, name, value): + self.values[name] = value + + +def git(path: Path, *args: str) -> str: + result = subprocess.run( + ["git", *args], cwd=path, capture_output=True, text=True, check=True, + ) + return result.stdout.strip() + + +def make_repo(tmp_path: Path) -> Path: + source = tmp_path / "source" + source.mkdir() + git(source, "init", "-b", "main") + git(source, "config", "user.name", "Updater Test") + git(source, "config", "user.email", "updater@example.test") + (source / "README.md").write_text("old\n", encoding="utf-8") + (source / "requirements.txt").write_text("example-package==1.0\n", encoding="utf-8") + git(source, "add", "README.md", "requirements.txt") + git(source, "commit", "-m", "initial") + checkout = tmp_path / "panel" + subprocess.run( + ["git", "clone", "--branch", "main", str(source), str(checkout)], + capture_output=True, text=True, check=True, + ) + git(checkout, "remote", "set-url", "origin", REPOSITORY_URL) + return checkout + + +def advance_source(source: Path, *, filename: str = "README.md") -> str: + (source / filename).parent.mkdir(parents=True, exist_ok=True) + (source / filename).write_text("new\n", encoding="utf-8") + git(source, "add", filename) + git(source, "commit", "-m", "next") + return git(source, "rev-parse", "HEAD") + + +def local_fetch(updater: Updater, source: Path): + def fetch() -> str: + git(updater.repo_dir, "fetch", "--no-tags", str(source), "refs/heads/main") + return git(updater.repo_dir, "rev-parse", "FETCH_HEAD") + + updater._fetch_remote = fetch + updater._install_requirements = lambda _target: None + + +class UpdaterTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="virsh-panel-updater-test-") + self.addCleanup(self.temp.cleanup) + self.tmp_path = Path(self.temp.name) + + def test_settings_and_token_never_reveal_secret(self): + checkout = make_repo(self.tmp_path) + store = MemoryStore() + updater = Updater(checkout, store) + updater.set_token("a-test-access-token-123") + settings = updater.settings() + self.assertEqual(settings["repository"], REPOSITORY_URL) + self.assertTrue(settings["token_configured"]) + self.assertTrue(settings["checkout_ready"]) + self.assertIsNone(settings["active_job_id"]) + self.assertIsNone(settings["last_job_id"]) + self.assertNotIn("a-test-access-token-123", repr(settings)) + with updater._git_auth() as env: + self.assertEqual(env["VIRSH_PANEL_GIT_TOKEN"], "a-test-access-token-123") + self.assertNotIn("a-test-access-token-123", Path(env["GIT_ASKPASS"]).read_text()) + updater.clear_token() + self.assertFalse(updater.settings()["token_configured"]) + + def test_check_is_read_only_and_reports_new_version(self): + checkout = make_repo(self.tmp_path) + updater = Updater(checkout, MemoryStore()) + current = git(checkout, "rev-parse", "HEAD") + updater._remote_head = lambda: current + self.assertEqual(updater.check()["status"], "current") + updater._remote_head = lambda: "a" * 40 + self.assertEqual(updater.check()["status"], "update_available") + self.assertEqual(git(checkout, "rev-parse", "HEAD"), current) + + def test_zip_or_dirty_checkout_is_rejected(self): + plain = self.tmp_path / "plain" + plain.mkdir() + with self.assertRaisesRegex(UpdateError, "Git"): + Updater(plain, MemoryStore()).check() + + checkout = make_repo(self.tmp_path) + (checkout / "README.md").write_text("user changes\n", encoding="utf-8") + updater = Updater(checkout, MemoryStore()) + with self.assertRaisesRegex(UpdateError, "未提交"): + updater.create_job() + with self.assertRaisesRegex(UpdateError, "未提交"): + updater.apply() + + def test_fast_forward_job_is_persisted_and_calls_restart(self): + checkout = make_repo(self.tmp_path) + source = self.tmp_path / "source" + old = git(checkout, "rev-parse", "HEAD") + target = advance_source(source) + store = MemoryStore() + updater = Updater(checkout, store) + updater.set_token("a-test-access-token-123") + local_fetch(updater, source) + queued = updater.create_job() + self.assertEqual(updater.settings()["active_job_id"], queued["job_id"]) + restarted = [] + result = updater.run_pending_job(restart=lambda: restarted.append(True)) + self.assertEqual(result["status"], "succeeded") + self.assertEqual(result["old_commit"], old) + self.assertEqual(result["new_commit"], target) + self.assertTrue(result["rollback_ref"].startswith("refs/virsh-panel/rollback/")) + self.assertEqual(updater.get_job(queued["job_id"]), result) + self.assertEqual(updater.settings()["last_job_id"], queued["job_id"]) + self.assertIsNone(updater.settings()["active_job_id"]) + self.assertEqual(restarted, [True]) + self.assertEqual(git(checkout, "rev-parse", "HEAD"), target) + self.assertEqual(git(checkout, "rev-parse", result["rollback_ref"]), old) + + def test_remote_history_rewrite_never_overwrites_local_code(self): + checkout = make_repo(self.tmp_path) + source = self.tmp_path / "source" + target = advance_source(source) + git(checkout, "config", "user.name", "Updater Test") + git(checkout, "config", "user.email", "updater@example.test") + (checkout / "README.md").write_text("local fork\n", encoding="utf-8") + git(checkout, "add", "README.md") + git(checkout, "commit", "-m", "local fork") + local = git(checkout, "rev-parse", "HEAD") + updater = Updater(checkout, MemoryStore()) + local_fetch(updater, source) + with self.assertRaisesRegex(UpdateError, "分叉"): + updater.apply() + self.assertEqual(git(checkout, "rev-parse", "HEAD"), local) + self.assertNotEqual(local, target) + + def test_failed_dependency_sync_leaves_code_unchanged(self): + checkout = make_repo(self.tmp_path) + source = self.tmp_path / "source" + advance_source(source) + updater = Updater(checkout, MemoryStore()) + local_fetch(updater, source) + old = git(checkout, "rev-parse", "HEAD") + + def fail_install(_target): + raise UpdateError("依赖失败", 502) + + updater._install_requirements = fail_install + with self.assertRaisesRegex(UpdateError, "依赖失败"): + updater.apply() + self.assertEqual(git(checkout, "rev-parse", "HEAD"), old) + + def test_git_url_rewrite_is_rejected_before_sending_token(self): + checkout = make_repo(self.tmp_path) + git(checkout, "config", "url.https://evil.example/.insteadOf", "https://g.luoli.live/") + updater = Updater(checkout, MemoryStore()) + updater.set_token("a-test-access-token-123") + with self.assertRaisesRegex(UpdateError, "URL 重写"): + updater.check() + + def test_new_code_cannot_track_private_data_or_submodules(self): + checkout = make_repo(self.tmp_path) + source = self.tmp_path / "source" + target = advance_source(source, filename="data/master.key") + updater = Updater(checkout, MemoryStore()) + local_fetch(updater, source) + old = git(checkout, "rev-parse", "HEAD") + with self.assertRaisesRegex(UpdateError, "数据目录"): + updater.apply() + self.assertEqual(git(checkout, "rev-parse", "HEAD"), old) + self.assertNotEqual(old, target) + + def test_failed_restart_is_persisted_without_hiding_applied_commit(self): + checkout = make_repo(self.tmp_path) + source = self.tmp_path / "source" + target = advance_source(source) + updater = Updater(checkout, MemoryStore()) + updater.set_token("a-test-access-token-123") + local_fetch(updater, source) + job = updater.create_job() + + def fail_restart(): + raise UpdateError("重启失败", 500) + + with self.assertRaisesRegex(UpdateError, "重启失败"): + updater.run_pending_job(restart=fail_restart) + stored = updater.get_job(job["job_id"]) + self.assertEqual(stored["status"], "failed") + self.assertEqual(stored["new_commit"], target) + self.assertTrue(stored["rollback_ref"]) + self.assertIn("代码可能已切换", stored["error"]) + + def test_checked_remote_commit_is_pinned_through_worker_execution(self): + checkout = make_repo(self.tmp_path) + source = self.tmp_path / "source" + old = git(checkout, "rev-parse", "HEAD") + checked = advance_source(source) + store = MemoryStore() + updater = Updater(checkout, store) + updater.set_token("a-test-access-token-123") + updater._remote_head = lambda: checked + local_fetch(updater, source) + queued = updater.create_job( + expected_current_commit=old, + expected_remote_commit=checked, + ) + advance_source(source, filename="VERSION") + with self.assertRaisesRegex(UpdateError, "main 分支已变化"): + updater.run_pending_job(restart=lambda: None) + self.assertEqual(git(checkout, "rev-parse", "HEAD"), old) + self.assertEqual(updater.get_job(queued["job_id"])["status"], "failed") + + def test_create_job_rejects_changed_remote_since_check(self): + checkout = make_repo(self.tmp_path) + updater = Updater(checkout, MemoryStore()) + updater.set_token("a-test-access-token-123") + updater._remote_head = lambda: "b" * 40 + with self.assertRaisesRegex(UpdateError, "main 分支已变化"): + updater.create_job( + expected_current_commit=git(checkout, "rev-parse", "HEAD"), + expected_remote_commit="a" * 40, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/tests/test_users.py b/engine/tests/test_users.py new file mode 100644 index 00000000..8ddf01d4 --- /dev/null +++ b/engine/tests/test_users.py @@ -0,0 +1,253 @@ +"""Exercise SQL-backed registration and ownership without a MariaDB daemon.""" + +from __future__ import annotations + +import sqlite3 +import uuid + +import pytest + +from virsh_panel.auth import verify_password +from virsh_panel.users import DatabaseUserStore, UserError, normalize_email + + +class _Cursor: + def __init__(self, connection: sqlite3.Connection) -> None: + self._cursor = connection.cursor() + + def __enter__(self): + return self + + def __exit__(self, *_exc): + self._cursor.close() + + def execute(self, statement, parameters=()): + sql = statement.replace("%s", "?").replace(" FOR UPDATE", "") + try: + self._cursor.execute(sql, parameters) + except sqlite3.IntegrityError as exc: + import pymysql + + raise pymysql.err.IntegrityError(1062, str(exc)) from exc + return self + + def fetchone(self): + row = self._cursor.fetchone() + return None if row is None else dict(row) + + def fetchall(self): + return [dict(row) for row in self._cursor.fetchall()] + + @property + def lastrowid(self): + return self._cursor.lastrowid + + @property + def rowcount(self): + return self._cursor.rowcount + + +class _Connection: + def __init__(self): + self.raw = sqlite3.connect(":memory:") + self.raw.row_factory = sqlite3.Row + self.raw.execute("PRAGMA foreign_keys=ON") + self.raw.executescript(""" + CREATE TABLE users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + email TEXT UNIQUE, + password_hash TEXT NOT NULL, + admin INTEGER NOT NULL DEFAULT 0, + approved INTEGER NOT NULL DEFAULT 0, + email_verified INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ); + CREATE TABLE registration_codes ( + email TEXT PRIMARY KEY, + code_hash TEXT NOT NULL, + sent_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + failed_attempts INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE vm_ownership ( + host_scope TEXT NOT NULL, + vm_uuid TEXT NOT NULL, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + PRIMARY KEY (host_scope, vm_uuid) + ); + """) + + def cursor(self): + return _Cursor(self.raw) + + def commit(self): + self.raw.commit() + + def rollback(self): + self.raw.rollback() + + def close(self): + # DatabaseUserStore opens a new wrapper per method. This one fake + # keeps a shared in-memory database alive across the test. + pass + + +class _Store: + def __init__(self): + self.connection = _Connection() + + def _connect(self): + return self.connection + + +@pytest.fixture +def users(): + store = _Store() + yield DatabaseUserStore(store, b"x" * 32), store.connection.raw + store.connection.raw.close() + + +def test_initial_user_is_not_admin_but_is_approved(users): + repository, _database = users + assert repository.has_users() is False + first = repository.create_initial_user("first", "initial-long-password", now=100) + assert first["admin"] is False + assert first["approved"] is True + assert first["email_verified"] is True + assert first["email"] is None + assert verify_password("initial-long-password", first["password_hash"]) + assert repository.has_users() is True + assert repository.get_by_username("first") == first + assert repository.get_by_id(first["id"]) == first + assert repository.get_by_email("first@example.test") is None + assert repository.get_by_email("first") is None + _database.execute("UPDATE users SET email=? WHERE id=?", ("first@example.test", first["id"])) + _database.commit() + assert repository.get_by_email("FIRST@EXAMPLE.TEST")["id"] == first["id"] + with pytest.raises(UserError) as repeated: + repository.create_initial_user("second", "another-long-password", now=101) + assert repeated.value.status == 409 + + +def test_initial_user_rejects_invalid_email_when_provided(users): + repository, _database = users + for email in ("", "not-an-email"): + with pytest.raises(UserError): + repository.create_initial_user("first", "initial-long-password", email) + assert repository.has_users() is False + + +def test_registration_code_is_keyed_rate_limited_and_one_time(users): + repository, database = users + assert repository.issue_registration_code("User@Example.COM", "123456", now=100) + code_hash = database.execute( + "SELECT code_hash FROM registration_codes WHERE email=?", ("user@example.com",) + ).fetchone()[0] + assert len(code_hash) == 64 + assert code_hash != "123456" + with pytest.raises(UserError) as cooldown: + repository.issue_registration_code("user@example.com", "654321", now=120) + assert cooldown.value.status == 429 + with pytest.raises(UserError): + repository.register_with_code("registered", "user@example.com", "long-user-password", "000000", now=130) + assert database.execute( + "SELECT failed_attempts FROM registration_codes WHERE email=?", ("user@example.com",) + ).fetchone()[0] == 1 + created = repository.register_with_code( + "registered", "USER@EXAMPLE.COM", "long-user-password", "123456", now=140, + ) + assert created["email"] == "user@example.com" + assert created["email_verified"] is True + assert created["admin"] is False + assert created["approved"] is False + assert verify_password("long-user-password", created["password_hash"]) + assert repository.issue_registration_code("user@example.com", "222222", now=300) is False + with pytest.raises(UserError): + repository.register_with_code( + "duplicate", "user@example.com", "long-user-password", "123456", now=145, + ) + + +def test_code_expires_and_five_failures_consume_challenge(users): + repository, database = users + repository.issue_registration_code("fail@example.com", "999999", now=100) + for attempt in range(5): + with pytest.raises(UserError): + repository.register_with_code( + "wrong", "fail@example.com", "long-user-password", "000000", now=110 + attempt, + ) + assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0 + with pytest.raises(UserError): + repository.register_with_code( + "wrong", "fail@example.com", "long-user-password", "999999", now=116, + ) + repository.issue_registration_code("expired@example.com", "111111", now=200) + with pytest.raises(UserError): + repository.register_with_code( + "expired", "expired@example.com", "long-user-password", "111111", now=800, + ) + assert database.execute( + "SELECT COUNT(*) FROM registration_codes WHERE email='expired@example.com'" + ).fetchone()[0] == 0 + + +def test_failed_smtp_delivery_can_revoke_only_matching_code(users): + repository, database = users + repository.issue_registration_code("retry@example.com", "111111", now=100) + assert repository.revoke_registration_code("retry@example.com", "222222") is False + assert repository.revoke_registration_code("retry@example.com", "111111") is True + assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0 + assert repository.issue_registration_code("retry@example.com", "333333", now=101) + + +def test_approval_and_manual_admin_flag_are_distinct(users): + repository, database = users + repository.issue_registration_code("awaiting@example.com", "123456", now=100) + account = repository.register_with_code( + "awaiting", "awaiting@example.com", "long-user-password", "123456", now=120, + ) + pending = repository.list_pending_users() + assert len(pending) == 1 and pending[0]["username"] == "awaiting" + assert "password_hash" not in pending[0] + approved = repository.approve_user(account["id"]) + assert approved["approved"] is True and approved["admin"] is False + assert repository.list_pending_users() == [] + database.execute("UPDATE users SET admin=1 WHERE id=?", (account["id"],)) + database.commit() + assert repository.get_by_username("awaiting")["admin"] is True + assert repository.approve_user(999999) is None + + +def test_vm_ownership_is_scoped_to_host_and_user(users): + repository, _database = users + first = repository.create_initial_user("first", "initial-long-password", now=100) + repository.issue_registration_code("other@example.com", "123456", now=101) + other = repository.register_with_code( + "other", "other@example.com", "long-user-password", "123456", now=102, + ) + host = "a" * 64 + second_host = "b" * 64 + vm_id = str(uuid.uuid4()) + assert repository.owner_of_vm(host, vm_id) is None + repository.assign_vm(host, vm_id, first["id"], now=103) + repository.assign_vm(host, vm_id, first["id"], now=103) + assert repository.owns_vm(host, vm_id, first["id"]) is True + assert repository.owns_vm(host, vm_id, other["id"]) is False + assert repository.list_owned_vm_ids(host, first["id"]) == {vm_id} + assert repository.list_owned_vm_ids(second_host, first["id"]) == set() + with pytest.raises(UserError) as conflict: + repository.assign_vm(host, vm_id, other["id"], now=104) + assert conflict.value.status == 409 + repository.delete_vm_owner(host, vm_id) + assert repository.owner_of_vm(host, vm_id) is None + + +@pytest.mark.parametrize("address", [ + "evil@example.com\r\nBcc: victim@example.com", "not-an-email", "x@localhost", + "a..b@example.com", "x@example..com", "ñ@example.com", +]) +def test_email_validation_rejects_unsafe_addresses(address): + with pytest.raises(UserError): + normalize_email(address) diff --git a/engine/virsh_panel/__init__.py b/engine/virsh_panel/__init__.py new file mode 100644 index 00000000..e620969e --- /dev/null +++ b/engine/virsh_panel/__init__.py @@ -0,0 +1 @@ +"""Remote libvirt web panel.""" diff --git a/engine/virsh_panel/app.py b/engine/virsh_panel/app.py new file mode 100644 index 00000000..5ae09a70 --- /dev/null +++ b/engine/virsh_panel/app.py @@ -0,0 +1,2532 @@ +"""Browser setup, authenticated API, and VM console for one remote host.""" + +from __future__ import annotations + +import asyncio +import hashlib +import hmac +import ipaddress +import json +import logging +import os +import subprocess +import tempfile +import threading +import time +import uuid +import xml.etree.ElementTree as ET +from concurrent.futures import ThreadPoolExecutor +from contextlib import asynccontextmanager, suppress +from pathlib import Path +from typing import Any, Callable, Literal +from urllib.parse import urlsplit + +from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Query, Request, WebSocket +from fastapi.responses import FileResponse, JSONResponse +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel, ConfigDict, Field, SecretStr + +from .auth import DatabaseSessionStore, LoginLimiter, Session, SessionStore, verify_password +from .cloud_init import _validate_guest_auth, generate_root_password, hash_root_password +from .cloud_templates import ( + TemplateError, TemplateStore, download_verified_image, image_version_for, template_id_for, + template_scope, template_volume_name, validate_template_name, +) +from .config import Settings +from .console import ConsoleRelayError, relay_console +from .database import DatabaseError, make_components +from .database_bootstrap import DatabaseBootstrap, DatabaseSetupError +from .libvirt_service import VMError, VMService +from .metrics import (MAX_QUERY_POINTS, RETENTION_SECONDS, RANGES, MetricsCollector, + host_scope, query_interval_seconds) +from .panel_state import PanelState, SetupError +from .remote_host import HostProfile, RemoteHostError, RemoteHostManager +from .rescue_templates import ( + MAX_RESCUE_ISO_BYTES, RescueTemplateStore, rescue_scope, + rescue_volume_name, verify_bootable_iso, +) +from .ssh_keys import SSHKeyError +from .smtp_service import SMTPError, SMTPSettingsStore, send_verification_code +from .updater import BRANCH, REPOSITORY_URL, UpdateError, Updater +from .users import UserError, normalize_email +from .engine_context import EngineComponents, TRUSTED_ACTOR, actor, actor_account, actor_session + + +COOKIE_NAME = "virsh_panel_session" +CONSOLE_ACCESS_CHECK_SECONDS = 15 +LOG = logging.getLogger(__name__) +STARTUP_LOG = logging.getLogger("uvicorn.error") + + +class SetupBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + token: str = Field(min_length=1, max_length=256) + username: str = Field(min_length=3, max_length=32) + password: str = Field(min_length=12, max_length=1024) + + +class DatabaseSetupBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + host: str = Field(min_length=1, max_length=253) + port: int = Field(ge=1, le=65535) + database: str = Field(min_length=1, max_length=64) + username: str = Field(min_length=1, max_length=128) + password: SecretStr + setup_token: str = Field(min_length=1, max_length=256) + + +class UpdateSettingsBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + repository_url: str = Field(default=REPOSITORY_URL, max_length=2048) + branch: str = Field(default=BRANCH, max_length=128) + access_token: SecretStr | None = None + + +class UpdateApplyBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + expected_current_commit: str = Field(pattern=r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$") + expected_remote_commit: str = Field(pattern=r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$") + + +class LoginBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + email: str | None = Field(default=None, min_length=3, max_length=254) + # Only the injected, database-free test harness may use the historical + # username login. Production explicitly rejects this field below. + username: str | None = Field(default=None, min_length=1, max_length=64) + password: str = Field(min_length=1, max_length=1024) + + +class RegistrationCodeBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + email: str = Field(min_length=3, max_length=254) + + +class RegistrationBody(RegistrationCodeBody): + username: str = Field(min_length=3, max_length=32) + password: str = Field(min_length=12, max_length=1024) + code: str = Field(pattern=r"^[0-9]{6}$") + + +class SMTPSettingsBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + host: str = Field(min_length=1, max_length=253) + port: int = Field(ge=1, le=65535) + tls_mode: Literal["ssl", "starttls", "none"] + username: str = Field(default="", max_length=256) + password: SecretStr | None = None + from_address: str = Field(min_length=3, max_length=254) + + +class UnlockBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + passphrase: str = Field(min_length=1, max_length=1024) + + +class HostScanBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + host: str = Field(min_length=1, max_length=253) + port: int = Field(ge=1, le=65535) + + +class HostBody(HostScanBody): + private_key: str = Field(default="", max_length=65536) + private_key_passphrase: str = Field(default="", max_length=1024) + host_key: str = Field(min_length=1, max_length=4096) + confirmed_fingerprint: str = Field(min_length=1, max_length=256) + storage_pool: str = Field(default="default", min_length=1, max_length=4096) + iso_pool: str = Field(default="iso", min_length=1, max_length=4096) + rescue_iso_pool: str = Field(default="", max_length=4096) + default_network: str = Field(default="default", min_length=1, max_length=128) + region: str = Field(default="", max_length=64, + pattern=r"^[^\x00-\x1f\x7f]*$") + public_pool_cidr: str = Field(default="", max_length=18) + public_gateway: str = Field(default="", max_length=15) + public_dns_servers: list[str] = Field(default_factory=list, max_length=4) + public_reserved_ips: list[str] = Field(default_factory=list, max_length=254) + public_vm_prefix: int | None = Field(default=None, ge=24, le=30) + + def profile(self) -> HostProfile: + return HostProfile( + host=self.host, + port=self.port, + private_key=self.private_key, + host_key=self.host_key, + private_key_passphrase=self.private_key_passphrase, + storage_pool=self.storage_pool, + iso_pool=self.iso_pool, + rescue_iso_pool=self.rescue_iso_pool, + default_network=self.default_network, + region=self.region, + public_pool_cidr=self.public_pool_cidr, + public_gateway=self.public_gateway, + public_dns_servers=self.public_dns_servers, + public_reserved_ips=self.public_reserved_ips, + public_vm_prefix=self.public_vm_prefix, + ) + + +class CreateISOBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + source: Literal["iso"] = "iso" + name: str = Field(min_length=1, max_length=63) + vcpu: int = Field(ge=1, le=64) + memory_mib: int = Field(ge=512, le=262144) + disk_gib: int = Field(ge=1, le=4096) + bandwidth_mbps: int | None = Field(default=None, ge=1, le=100000) + network: str = Field(min_length=1, max_length=128) + iso: str = Field(min_length=1, max_length=255) + + +class CreateCloudBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + source: Literal["cloud"] + name: str = Field(min_length=1, max_length=63) + vcpu: int = Field(ge=1, le=64) + memory_mib: int = Field(ge=512, le=262144) + disk_gib: int = Field(ge=1, le=4096) + bandwidth_mbps: int | None = Field(default=None, ge=1, le=100000) + network: str = Field(min_length=1, max_length=128) + template_id: str = Field(min_length=1, max_length=80) + public_ip_cidr: str = Field(default="", max_length=64) + gateway: str = Field(default="", max_length=64) + dns_servers: list[str] = Field(default_factory=list, max_length=4) + guest_ssh_public_key: str = Field(default="", max_length=16384) + guest_ssh_key_id: int | None = Field(default=None, ge=1) + root_password: SecretStr | None = None + + +class SSHKeyBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + name: str = Field(min_length=1, max_length=80) + public_key: str = Field(min_length=1, max_length=16384) + + +class ImportTemplateBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + url: str = Field(min_length=16, max_length=2048) + sha256: str = Field(min_length=64, max_length=64) + name: str = Field(min_length=1, max_length=64) + + +class RenameTemplateBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + name: str = Field(min_length=1, max_length=64) + + +class ReinstallBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + template_id: str = Field(min_length=1, max_length=80) + ssh_public_key: str = Field(default="", max_length=16384) + ssh_key_id: int | None = Field(default=None, ge=1) + root_password: SecretStr | None = None + confirmation_name: str = Field(min_length=1, max_length=63) + + +class EnterRescueBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + template_id: str = Field(pattern=r"^[0-9a-f]{32}$") + confirmation_name: str = Field(min_length=1, max_length=63) + + +class ExitRescueBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + confirmation_name: str = Field(min_length=1, max_length=63) + + +class ForceRescueBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + confirmation_name: str = Field(min_length=1, max_length=63) + ack_data_loss: Literal[True] + + +class ActionBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + action: Literal["start", "shutdown", "reboot", "poweroff", "reset"] + + +def _public_host(profile: dict | None) -> dict: + if profile is None: + return {"configured": False} + keys = ( + "host", "port", "key_type", "fingerprint", "storage_pool", + "iso_pool", "default_network", "private_key_configured", + "private_key_encrypted", "key_locked", "private_key_passphrase_saved", + ) + return { + "configured": True, + **{key: profile[key] for key in keys if key in profile}, + "rescue_iso_pool": profile.get("rescue_iso_pool", ""), + "region": profile.get("region", ""), + "public_pool_cidr": profile.get("public_pool_cidr", ""), + "public_gateway": profile.get("public_gateway", ""), + "public_dns_servers": profile.get("public_dns_servers", []), + "public_reserved_ips": profile.get("public_reserved_ips", []), + "public_vm_prefix": profile.get("public_vm_prefix"), + } + + +def _peer(request: Request) -> str: + # Uvicorn has already processed forwarding headers from its trusted local + # reverse proxy. Never read a raw client-supplied X-Real-IP here, because + # that would let a login attacker reset the rate limit. + return request.client.host if request.client else "unknown" + + +def _origin_matches_host(origin: str | None, host: str | None) -> bool: + if not origin or not host: + return False + try: + parsed = urlsplit(origin) + except ValueError: + return False + if parsed.scheme != "https": + return False + return bool( + parsed.netloc == host + and parsed.hostname + and not parsed.username + and not parsed.password + and not parsed.path + and not parsed.query + and not parsed.fragment + ) + + +def _plain_loopback_allowed(scope: dict, host: str | None) -> bool: + """Permit local diagnostics only when both peer and requested host are local. + + The request scheme is supplied by the ASGI server. Uvicorn's proxy header + handling may upgrade it to HTTPS/WSS only for its explicitly trusted proxy + address; this function never trusts an incoming forwarding header itself. + """ + client = scope.get("client") + if not client or not host: + return False + try: + peer_is_local = ipaddress.ip_address(client[0]).is_loopback + host_is_local = urlsplit("//" + host).hostname in { + "localhost", "127.0.0.1", "::1", + } + except ValueError: + return False + return peer_is_local and host_is_local + + +def create_app( + settings: Settings | None = None, + *, + panel_state: PanelState | None = None, + remote_manager: RemoteHostManager | None = None, + service_factory: Callable[[dict], VMService] | None = None, + metric_store: Any | None = None, + engine_components: EngineComponents | None = None, +) -> FastAPI: + settings = settings or Settings.from_env() + settings.validate() + # Injected objects keep the existing isolated HTTP test harness working. + # Normal production startup never uses the old JSON-backed stores. + internal_mode = engine_components is not None + database_mode = internal_mode or (panel_state is None and remote_manager is None) + bootstrap = DatabaseBootstrap(settings.data_dir) if database_mode and not internal_mode else None + data_store = None + updater = None + if internal_mode: + state = engine_components.state + manager = engine_components.manager + templates = engine_components.templates + data_store = engine_components.store + metric_store = engine_components.metric_store + setup_token = None + elif database_mode: + configured_database = bootstrap.load_config() + if configured_database is None: + setup_token = bootstrap.ensure_token() + state = None + manager = None + templates = None + else: + state, manager, templates, data_store = make_components( + settings.data_dir, configured_database, bootstrap.master_key(), + settings.ssh_binary, + ) + setup_token = (bootstrap.ensure_token() + if state.setup_required() else state.initialize_setup_token()) + else: + state = panel_state or PanelState(settings.data_dir) + setup_token = state.initialize_setup_token() + manager = remote_manager or RemoteHostManager( + settings.data_dir, ssh_binary=settings.ssh_binary) + templates = TemplateStore(settings.data_dir) + if setup_token is not None: + # Uvicorn writes this logger to stderr, which the supplied systemd + # service captures in its journal. Never expose the token over HTTP. + STARTUP_LOG.warning("VIRSH_PANEL_SETUP_TOKEN=%s", setup_token) + if database_mode and (settings.data_dir / "generations").exists(): + STARTUP_LOG.warning( + "Legacy data/generations detected; its old SSH key files are not migrated " + "or automatically removed. Verify and remove them separately." + ) + import_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="cloud-image-import") + import_lock = threading.RLock() + import_jobs: dict[str, dict] = {} + pending_templates: set[tuple[str, str]] = set() + rescue_catalog = RescueTemplateStore(data_store) + rescue_import_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="rescue-iso-import") + rescue_import_lock = threading.RLock() + rescue_import_jobs: dict[str, dict] = {} + pending_rescue_imports: set[str] = set() + reinstall_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="vm-reinstall") + reinstall_lock = threading.RLock() + reinstall_jobs: dict[str, dict] = {} + pending_reinstalls: set[tuple[str, str]] = set() + rescue_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="vm-rescue") + rescue_lock = threading.RLock() + rescue_jobs: dict[str, dict] = {} + pending_rescues: set[tuple[str, str]] = set() + test_rescue_states: dict[str, str] = {} + # The production store encrypts each credential record with a fresh AES-GCM + # nonce. The in-memory fallback is only for injected, database-free tests. + test_credentials: dict[str, str] = {} + + def ip_claim_key(profile: dict, address: str) -> str: + return f"{host_scope(profile)}.{address}" + + def insert_public_ip_claim(profile: dict, address: str, vm_id: str) -> bool: + if data_store is None: + return True + claim = json.dumps({"vm_uuid": vm_id, "reserved_at": int(time.time())}, + separators=(",", ":")) + return data_store.insert("ip_claim", ip_claim_key(profile, address), claim) + + def allocate_public_ip(profile: dict, service: VMService, + vm_id: str) -> str: + """Choose and reserve a public IP, including across panel processes. + + Claims remain after a successful create and are released on panel VM + deletion. A claim from an uncertain create is retained rather than + risking reuse of an address whose guest may still exist. + """ + try: + network = ipaddress.IPv4Network(profile["public_pool_cidr"], strict=True) + gateway = ipaddress.IPv4Address(profile["public_gateway"]) + guest_prefix = profile.get("public_vm_prefix") + if guest_prefix is None: + guest_prefix = network.prefixlen + if (not 24 <= network.prefixlen <= 30 + or not network.network_address.is_global + or not network.broadcast_address.is_global + or gateway not in network + or gateway in (network.network_address, network.broadcast_address) + or isinstance(guest_prefix, bool) + or not isinstance(guest_prefix, int) + or not 24 <= guest_prefix <= network.prefixlen): + raise ValueError("Invalid host public IPv4 pool") + blocked = {network.network_address, network.broadcast_address, gateway} + for value in (*profile.get("public_reserved_ips", []), + *profile.get("public_dns_servers", [])): + address = ipaddress.ip_address(value) + if isinstance(address, ipaddress.IPv4Address) and address in network: + blocked.add(address) + try: + host_address = ipaddress.ip_address(profile["host"]) + except ValueError: + host_address = None + if isinstance(host_address, ipaddress.IPv4Address) and host_address in network: + blocked.add(host_address) + except (KeyError, TypeError, ValueError) as exc: + raise VMError("宿主机公网地址池配置损坏,请管理员重新保存设置", 500) from exc + + # Include all libvirt-visible panel IPs, regardless of VM ownership. + # VMService also checks duplicates under its own create lock. + for existing_vm in service.list_vms(): + configured = existing_vm.get("public_ip_cidr") + if isinstance(configured, str): + try: + address = ipaddress.IPv4Address(configured.split("/", 1)[0]) + except ValueError: + continue + if address in network: + blocked.add(address) + + scope_prefix = f"{host_scope(profile)}." + if data_store is not None: + for key in data_store.list("ip_claim"): + if key.startswith(scope_prefix): + try: + address = ipaddress.IPv4Address(key[len(scope_prefix):]) + except ValueError: + continue + if address in network: + blocked.add(address) + + for address in network.hosts(): + if address in blocked: + continue + if not insert_public_ip_claim(profile, str(address), vm_id): + continue + return f"{address}/{guest_prefix}" + raise VMError("公网地址池中没有可分配的 IP,请检查已用和保留地址", 409) + + def claim_explicit_public_ip(profile: dict, public_ip_cidr: str, + vm_id: str) -> None: + if data_store is None: + return + try: + address = str(ipaddress.IPv4Interface(public_ip_cidr).ip) + except (TypeError, ValueError): + # The libvirt create path returns the detailed input error. + return + if not insert_public_ip_claim(profile, address, vm_id): + raise VMError("该公网 IP 已被面板中的虚拟机或创建任务占用", 409) + + def release_public_ip_claim(profile: dict, public_ip_cidr: str, + vm_id: str) -> None: + if data_store is None: + return + try: + address = str(ipaddress.IPv4Interface(public_ip_cidr).ip) + key = ip_claim_key(profile, address) + except (TypeError, ValueError, KeyError): + return + raw = data_store.get("ip_claim", key) + if raw is None: + return + try: + claim = json.loads(raw) + except (TypeError, ValueError): + LOG.error("Could not parse public IP claim for %s", key) + return + if isinstance(claim, dict) and claim.get("vm_uuid") == vm_id: + data_store.delete("ip_claim", key) + + def release_vm_public_ip_claims(profile: dict, vm_id: str) -> None: + if data_store is None: + return + prefix = f"{host_scope(profile)}." + for key, raw in data_store.list("ip_claim").items(): + if not key.startswith(prefix): + continue + try: + claim = json.loads(raw) + except (TypeError, ValueError): + LOG.error("Could not parse public IP claim for %s", key) + continue + if isinstance(claim, dict) and claim.get("vm_uuid") == vm_id: + data_store.delete("ip_claim", key) + + def credential_key(profile: dict, vm_id: str) -> str: + try: + canonical_id = str(uuid.UUID(vm_id)) + return f"{host_scope(profile)}.{canonical_id}" + except (TypeError, ValueError, AttributeError, KeyError) as exc: + raise VMError("虚拟机或宿主机身份信息无效", 400) from exc + + def save_credential(profile: dict, vm_id: str, auth_mode: str, + generation: str, password: str | None = None) -> None: + key = credential_key(profile, vm_id) + if not isinstance(generation, str) or not generation: + raise ValueError("虚拟机系统配置代号无效") + value = json.dumps({"auth_mode": auth_mode, "password": password, + "generation": generation}, + ensure_ascii=False, separators=(",", ":")) + if data_store is not None: + data_store.set("vm_credential", key, value) + else: + test_credentials[key] = value + + def delete_credential(profile: dict, vm_id: str) -> None: + key = credential_key(profile, vm_id) + if data_store is not None: + data_store.delete("vm_credential", key) + else: + test_credentials.pop(key, None) + + def rescue_state_key(profile: dict, vm_id: str) -> str: + return credential_key(profile, vm_id) + + def rescue_xml_matches(first: str, second: str) -> bool: + try: + return ET.canonicalize(first) == ET.canonicalize(second) + except (TypeError, ET.ParseError): + return False + + def load_rescue_state(profile: dict, vm_id: str) -> dict | None: + key = rescue_state_key(profile, vm_id) + raw = (data_store.get("vm_rescue", key) if data_store is not None + else test_rescue_states.get(key)) + if raw is None: + return None + try: + record = json.loads(raw) + except (TypeError, ValueError) as exc: + raise DatabaseError("虚拟机救援记录损坏") from exc + if (not isinstance(record, dict) + or not isinstance(record.get("original_xml"), str) + or not record["original_xml"].startswith(" None: + key = rescue_state_key(profile, vm_id) + value = json.dumps(record, ensure_ascii=False, separators=(",", ":")) + if data_store is not None: + data_store.set("vm_rescue", key, value) + else: + test_rescue_states[key] = value + + def delete_rescue_state(profile: dict, vm_id: str) -> None: + key = rescue_state_key(profile, vm_id) + if data_store is not None: + data_store.delete("vm_rescue", key) + else: + test_rescue_states.pop(key, None) + + def current_rescue_state(profile: dict, vm_id: str, + service: VMService | None = None) -> dict | None: + """Clear a stale record only when the original inactive XML is intact. + + An interrupted worker may have stopped before changing the VM. The + database job is marked failed on restart, but its recovery record must + not indefinitely block normal operations in that safe case. + Callers hold rescue_lock so this cannot race a live rescue worker. + """ + record = load_rescue_state(profile, vm_id) + if record is None or (host_scope(profile), vm_id) in pending_rescues: + return record + service = service or new_service(profile) + current_vm = service.get_vm(vm_id) + if current_vm.get("rescue_mode") or current_vm.get("rescue_staged"): + return record + try: + original_still_defined = rescue_xml_matches( + service.prepare_rescue_vm(vm_id, record["volume_name"]), + record["original_xml"], + ) + except VMError: + return record + if original_still_defined: + delete_rescue_state(profile, vm_id) + return None + return record + + def parse_credential(raw: str | None) -> dict | None: + if raw is None: + return None + try: + value = json.loads(raw) + except (TypeError, ValueError) as exc: + raise DatabaseError("虚拟机登录凭据记录损坏") from exc + if (not isinstance(value, dict) + or value.get("auth_mode") not in ("password", "ssh_key", "ssh_key_password") + or (value["auth_mode"] in ("password", "ssh_key_password") + and (not isinstance(value.get("password"), str) + or not value["password"])) + or not isinstance(value.get("generation"), str) + or not value["generation"] + or (value["auth_mode"] == "ssh_key" and value.get("password") is not None)): + raise DatabaseError("虚拟机登录凭据记录损坏") + return value + + def get_credential(profile: dict, vm_id: str) -> dict | None: + key = credential_key(profile, vm_id) + raw = (data_store.get("vm_credential", key) if data_store is not None + else test_credentials.get(key)) + return parse_credential(raw) + + def decorate_vm(vm: dict, credential: dict | None, profile: dict) -> dict: + cloud = bool(vm.get("managed") and vm.get("os_source") == "cloud_template") + current_credential = (credential if cloud and credential + and credential["generation"] == vm.get("credential_generation") + else None) + return { + **{key: value for key, value in vm.items() if key != "credential_generation"}, + "region": profile.get("region", ""), + "login_name": "root" if cloud else None, + "auth_mode": current_credential["auth_mode"] if current_credential else "unknown", + "password_available": bool(current_credential and + current_credential["auth_mode"] in ( + "password", "ssh_key_password")), + } + + def save_job(kind: str, job_id: str, job: dict) -> None: + delegated = TRUSTED_ACTOR.get() if internal_mode else None + if delegated and delegated.get("operation_id"): + job.setdefault("operation_id", delegated["operation_id"]) + if data_store is not None: + data_store.set(kind, job_id, json.dumps( + job, ensure_ascii=False, separators=(",", ":"))) + + def delete_job(kind: str, job_id: str) -> None: + if data_store is not None: + data_store.delete(kind, job_id) + + def restore_jobs() -> None: + """Expose interrupted jobs as failed, never pretend work resumed.""" + if data_store is None: + return + for kind, destination in (("import_job", import_jobs), + ("reinstall_job", reinstall_jobs), + ("rescue_import_job", rescue_import_jobs), + ("rescue_job", rescue_jobs)): + for job_id, raw in data_store.list(kind).items(): + try: + job = json.loads(raw) + except (TypeError, ValueError) as exc: + raise DatabaseError("数据库任务记录损坏") from exc + if not isinstance(job, dict): + raise DatabaseError("数据库任务记录损坏") + if job.get("status") in {"queued", "running"}: + job["status"] = "failed" + job["phase"] = "面板重启,任务已中断" + job["error"] = "面板在任务执行期间重启;请检查宿主机实际状态,勿直接重复提交" + save_job(kind, job_id, job) + destination[job_id] = job + + restore_jobs() + sessions = DatabaseSessionStore(data_store) if data_store is not None else SessionStore() + login_limiter = LoginLimiter() + registration_limiter = LoginLimiter() + code_send_limiter = LoginLimiter() + setup_limiter = LoginLimiter() + unlock_limiter = LoginLimiter() + def metric_profile(): + if manager is None: + return None + background = getattr(manager, "current_for_background", None) + return background() if callable(background) else manager.current() + + metric_collector = MetricsCollector( + lambda: metric_store if metric_store is not None else data_store, + metric_profile, + lambda profile: new_service(profile), + ) if database_mode else None + + @asynccontextmanager + async def lifespan(_app: FastAPI): + if metric_collector is not None: + metric_collector.start() + try: + yield + finally: + if metric_collector is not None: + metric_collector.close() + reinstall_executor.shutdown(wait=True, cancel_futures=False) + import_executor.shutdown(wait=True, cancel_futures=False) + rescue_executor.shutdown(wait=True, cancel_futures=False) + rescue_import_executor.shutdown(wait=True, cancel_futures=False) + close_manager = getattr(manager, "close", None) if manager is not None else None + if callable(close_manager): + close_manager() + + app = FastAPI(title="Virsh Panel API", docs_url=None, redoc_url=None, lifespan=lifespan) + + app.mount("/static", StaticFiles(directory=str(settings.static_dir)), name="static") + app.mount( + "/vendor/novnc", + StaticFiles(directory=str(settings.static_dir / "vendor" / "novnc")), + name="novnc", + ) + + @app.middleware("http") + async def security_headers(request: Request, call_next): + if not internal_mode and request.url.scheme != "https" and not ( + request.url.path == "/api/v1/health" + and request.url.scheme == "http" + and _plain_loopback_allowed(request.scope, request.headers.get("host")) + ): + return JSONResponse(status_code=400, content={"error": "请使用 HTTPS 访问面板"}) + response = await call_next(request) + response.headers["X-Content-Type-Options"] = "nosniff" + response.headers["Referrer-Policy"] = "no-referrer" + response.headers["X-Frame-Options"] = "DENY" + response.headers["Content-Security-Policy"] = ( + "default-src 'self'; script-src 'self'; style-src 'self'; " + "img-src 'self' data:; connect-src 'self' wss:; " + "object-src 'none'; frame-ancestors 'none'; base-uri 'self'" + ) + if (request.url.path == "/" or request.url.path.startswith("/api/") + or request.url.path in ("/static/app.js", "/static/styles.css")): + response.headers["Cache-Control"] = "no-store" + return response + + @app.exception_handler(VMError) + async def handle_vm_error(_request: Request, exc: VMError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(RemoteHostError) + async def handle_remote_error(_request: Request, exc: RemoteHostError): + content = {"error": str(exc)} + if exc.status == 423: + content["error_code"] = "key_locked" + return JSONResponse(status_code=exc.status, content=content) + + @app.exception_handler(SetupError) + async def handle_setup_error(_request: Request, exc: SetupError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(DatabaseSetupError) + async def handle_database_setup_error(_request: Request, exc: DatabaseSetupError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(DatabaseError) + async def handle_database_error(_request: Request, exc: DatabaseError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(UpdateError) + async def handle_update_error(_request: Request, exc: UpdateError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(TemplateError) + async def handle_template_error(_request: Request, exc: TemplateError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(UserError) + async def handle_user_error(_request: Request, exc: UserError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(SMTPError) + async def handle_smtp_error(_request: Request, exc: SMTPError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(SSHKeyError) + async def handle_ssh_key_error(_request: Request, exc: SSHKeyError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + def account_for_session(session: Session) -> dict: + if internal_mode: + return actor_account(session) + if database_mode: + if state is None: + raise HTTPException(status_code=401, detail="请先登录") + user_id = getattr(session, "user_id", None) + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise HTTPException(status_code=401, detail="账号不可用,请重新登录") + account = state.users.get_by_id(user_id) + if (account is None or account["username"] != session.username + or not account["email_verified"]): + raise HTTPException(status_code=401, detail="账号不可用,请重新登录") + return account + # The injected JSON state is retained solely for the isolated HTTP + # test harness; production authorization always uses the users table. + return {"id": 0, "username": session.username, "admin": True, + "approved": True, "email_verified": True} + + def host_ready() -> bool: + if manager is None: + return False + profile = manager.current() + return profile is not None and not profile.get("key_locked", False) + + def require_session(request: Request) -> Session: + if internal_mode: + return actor_session() + session = sessions.get(request.cookies.get(COOKIE_NAME)) + if session is None: + raise HTTPException(status_code=401, detail="请先登录") + account_for_session(session) + return session + + def require_write(request: Request) -> Session: + session = require_session(request) + if internal_mode: + if not actor()["can_manage"]: + raise HTTPException(status_code=403, detail="当前账户不能执行虚拟机操作") + return session + csrf = request.headers.get("X-CSRF-Token", "") + if not hmac.compare_digest(csrf, session.csrf_token): + raise HTTPException(status_code=403, detail="请求验证失败") + return session + + def require_admin(request: Request) -> Session: + session = require_session(request) + if not account_for_session(session)["admin"]: + raise HTTPException(status_code=403, detail="仅管理员可以执行此操作") + return session + + def require_admin_write(request: Request) -> Session: + session = require_write(request) + if internal_mode and not actor()["is_super_admin"]: + raise HTTPException(status_code=403, detail="只有超级管理员可以修改宿主机或镜像") + if not account_for_session(session)["admin"]: + raise HTTPException(status_code=403, detail="仅管理员可以执行此操作") + return session + + def require_approved(request: Request) -> Session: + session = require_session(request) + account = account_for_session(session) + if not account["admin"] and not account["approved"]: + raise HTTPException(status_code=403, detail="账号等待管理员批准") + return session + + def require_approved_write(request: Request) -> Session: + session = require_write(request) + account = account_for_session(session) + if not account["admin"] and not account["approved"]: + raise HTTPException(status_code=403, detail="账号等待管理员批准") + return session + + def require_vm_access(session: Session, profile: dict, vm_id: str) -> str: + if not database_mode: + return vm_id + try: + canonical_id = str(uuid.UUID(vm_id)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效", 400) from exc + account = account_for_session(session) + if not account["admin"] and not state.users.owns_vm( + host_scope(profile), canonical_id, account["id"]): + raise VMError("虚拟机不存在", 404) + return canonical_id + + def smtp_store() -> SMTPSettingsStore: + if data_store is None: + raise SMTPError("请先完成数据库配置", 409) + return SMTPSettingsStore(data_store) + + def ssh_key_store(): + if not database_mode or state is None: + raise SSHKeyError("请先完成数据库配置", 409) + return state.ssh_keys + + def current_updater() -> Updater: + nonlocal updater + if data_store is None: + raise UpdateError("请先完成数据库配置", 409) + if updater is None: + updater = Updater(settings.static_dir.parent, data_store) + return updater + + def forbid_long_job_during_update() -> None: + if data_store is None: + return + active_id = data_store.get_value("update.active_job") + if active_id: + job = current_updater().get_job(active_id) + if job is not None and job.get("status") in {"queued", "running"}: + raise HTTPException(status_code=409, detail="面板正在更新,暂时不能开始新任务") + + def current_profile() -> dict: + profile = manager.current() + if profile is None: + raise HTTPException(status_code=409, detail="请先在面板中配置宿主机") + if profile.get("key_locked"): + raise RemoteHostError("宿主机 SSH 私钥已锁定,请先在面板解锁", 423) + return profile + + def new_service(profile: dict) -> VMService: + if service_factory is not None: + return service_factory(profile) + return VMService( + profile["libvirt_uri"], + profile["storage_pool"], + profile["iso_pool"], + profile["default_network"], + rescue_iso_pool=profile.get("rescue_iso_pool", ""), + ) + + def verified_created_vm(profile: dict, result: dict, requested_uuid: str) -> dict: + if result.get("uuid") == requested_uuid: + return result + # Keep the preallocated owner/credential records if libvirt may have + # created the requested guest. Never delete a returned, mismatched UUID: + # it may refer to a different existing VM. + LOG.error("VM create returned a mismatched UUID: expected=%s", requested_uuid) + try: + verified = new_service(profile).get_vm(requested_uuid) + except VMError: + verified = None + if verified is not None and verified.get("uuid") == requested_uuid: + LOG.warning("Recovered VM result by querying the requested UUID: %s", requested_uuid) + return verified + raise VMError("虚拟机创建结果与预分配 UUID 不一致;请由管理员核查宿主机及归属记录", 502) + + def current_service() -> VMService: + return new_service(current_profile()) + + def validate_staged_libvirt( + staged, body: HostBody, *, ensure_paths: bool = False, + ) -> tuple[dict | None, str | None]: + service = new_service({ + "libvirt_uri": staged.libvirt_uri, + "storage_pool": body.storage_pool, + "iso_pool": body.iso_pool, + "rescue_iso_pool": body.rescue_iso_pool, + "default_network": body.default_network, + }) + # A successful libvirt API call is required before activation. Missing + # storage/network resources should not prevent connecting an otherwise + # healthy host; the UI can guide the operator to fix those separately. + service.list_vms() + if ensure_paths and (body.rescue_iso_pool or any(path.startswith("/") for path in ( + body.storage_pool, body.iso_pool))): + service.ensure_storage_pools() + try: + return service.resources(), None + except VMError as exc: + return None, str(exc) + + def session_response(username: str) -> JSONResponse: + if database_mode: + account = state.users.get_by_username(username) + if account is None: + raise HTTPException(status_code=401, detail="账号不可用,请重新登录") + session = sessions.issue(username, user_id=account["id"]) + else: + session = sessions.issue(username) + account = account_for_session(session) + response = JSONResponse({ + "authenticated": True, + "username": session.username, + "csrf_token": session.csrf_token, + "admin": account["admin"], + "approved": account["approved"], + "host_ready": host_ready(), + }) + response.set_cookie( + COOKIE_NAME, + session.token, + max_age=8 * 60 * 60, + httponly=True, + secure=settings.secure_cookie, + samesite="strict", + path="/", + ) + return response + + @app.get("/", include_in_schema=False) + def index(): + return FileResponse(settings.static_dir / "index.html") + + @app.get("/api/v1/health") + def health(): + if data_store is not None: + # A running HTTP listener alone is not a usable post-update panel. + # The updater treats this endpoint as readiness for the configured DB. + if database_mode: + state.users.has_users() + else: + data_store.get("admin", "singleton") + return {"status": "ok"} + + @app.get("/api/v1/database/status") + def database_status(): + if bootstrap is None: + return {"configured": True, "setup_required": False} + return {"configured": bootstrap.configured(), + "setup_required": not bootstrap.configured()} + + @app.post("/api/v1/database/setup") + def setup_database(body: DatabaseSetupBody, request: Request): + nonlocal state, manager, templates, data_store, updater, sessions, rescue_catalog + if bootstrap is None: + raise DatabaseSetupError("数据库初始化仅供正常部署使用", 409) + peer = _peer(request) + if not setup_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="初始化尝试过多,请稍后再试") + + def connect(config: dict, master_key: bytes): + try: + return make_components( + settings.data_dir, config, master_key, settings.ssh_binary) + except Exception as exc: + # Connector errors may include database host details. Never + # reflect the exception, credentials or driver SQL in HTTP. + LOG.warning("database setup connection failed: %s", type(exc).__name__) + raise DatabaseSetupError( + "无法连接或初始化 MariaDB;请检查地址、账号、数据库和建表权限", 502, + ) from exc + + try: + components = bootstrap.configure({ + "host": body.host, + "port": body.port, + "database": body.database, + "username": body.username, + "password": body.password.get_secret_value(), + }, body.setup_token, connect) + except DatabaseSetupError: + setup_limiter.failed(peer) + raise + state, manager, templates, data_store = components + rescue_catalog = RescueTemplateStore(data_store) + sessions = DatabaseSessionStore(data_store) + restore_jobs() + setup_limiter.succeeded(peer) + LOG.info("panel database configured") + return {"configured": True} + + @app.get("/api/v1/setup/status") + def setup_status(): + if state is None: + raise HTTPException(status_code=409, detail="请先配置数据库") + return {"setup_required": state.setup_required()} + + @app.post("/api/v1/setup/admin") + def setup_admin(body: SetupBody, request: Request): + if state is None: + raise HTTPException(status_code=409, detail="请先配置数据库") + peer = _peer(request) + if not setup_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="初始化尝试过多,请稍后再试") + try: + username = state.create_admin(body.token, body.username, body.password) + except SetupError: + setup_limiter.failed(peer) + raise + setup_limiter.succeeded(peer) + LOG.info("panel initial user created: username=%s", username) + return session_response(username) + + @app.get("/api/v1/session") + def session_info(request: Request): + session = sessions.get(request.cookies.get(COOKIE_NAME)) + if session is None: + return {"authenticated": False, "username": None, "csrf_token": None} + try: + account = account_for_session(session) + except HTTPException: + return {"authenticated": False, "username": None, "csrf_token": None} + return { + "authenticated": True, + "username": session.username, + "csrf_token": session.csrf_token, + "admin": account["admin"], + "approved": account["approved"], + "host_ready": host_ready(), + } + + @app.post("/api/v1/login") + def login(body: LoginBody, request: Request): + if state is None: + raise HTTPException(status_code=409, detail="请先配置数据库") + peer = _peer(request) + if not login_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="登录尝试过多,请稍后再试") + if database_mode: + if body.email is None or body.username is not None: + raise HTTPException(status_code=422, detail="请使用邮箱登录") + try: + email = normalize_email(body.email) + except UserError: + login_limiter.failed(peer) + raise HTTPException(status_code=401, detail="邮箱或密码错误") from None + if not state.users.has_users(): + raise HTTPException(status_code=409, detail="请先完成初始化") + account = state.users.get_by_email(email) + encoded = account["password_hash"] if account else None + username = account["username"] if account else "" + identity_ok = account is not None + else: + legacy_admin = state.admin() + if legacy_admin is None: + raise HTTPException(status_code=409, detail="请先完成初始化") + username, encoded = legacy_admin + account = {"email_verified": True} + identity_ok = hmac.compare_digest(body.username or "", username) + password_ok = verify_password(body.password, encoded) if encoded else False + if not password_ok or not identity_ok or not account["email_verified"]: + login_limiter.failed(peer) + raise HTTPException(status_code=401, detail="邮箱或密码错误") + login_limiter.succeeded(peer) + return session_response(username) + + def deliver_registration_code(config, email: str, code: str, users) -> None: + try: + send_verification_code(config, email, code) + except Exception as exc: + # Background delivery must not expose whether an email exists or + # relay SMTP server diagnostics to an unauthenticated client. + LOG.warning("Registration email delivery failed: %s", type(exc).__name__) + try: + users.revoke_registration_code(email, code) + except DatabaseError: + LOG.exception("Could not revoke undelivered registration code") + + @app.post("/api/v1/register/code") + def send_registration_code(body: RegistrationCodeBody, request: Request, + background_tasks: BackgroundTasks): + if not database_mode or state is None or not state.users.has_users(): + raise HTTPException(status_code=409, detail="请先完成面板初始化") + peer = _peer(request) + if not code_send_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="验证码请求过多,请稍后再试") + email = normalize_email(body.email) + config = smtp_store().get() + if config is None: + raise SMTPError("管理员尚未配置 SMTP,暂不能注册", 503) + code = state.users.generate_code() + try: + should_send = state.users.issue_registration_code(email, code) + except UserError as exc: + if exc.status != 429: + raise + should_send = False + code_send_limiter.failed(peer) + if should_send: + # Sending after the HTTP response avoids exposing whether an + # address is registered via SMTP latency or transport failures. + background_tasks.add_task( + deliver_registration_code, config, email, code, state.users, + ) + # Identical public response for existing addresses and cooldowns. + return {"sent": True} + + @app.post("/api/v1/register", status_code=201) + def register(body: RegistrationBody, request: Request): + if not database_mode or state is None or not state.users.has_users(): + raise HTTPException(status_code=409, detail="请先完成面板初始化") + peer = _peer(request) + if not registration_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="注册尝试过多,请稍后再试") + try: + state.users.register_with_code(body.username, body.email, + body.password, body.code) + except UserError: + registration_limiter.failed(peer) + raise + registration_limiter.succeeded(peer) + return {"registered": True, "approved": False} + + @app.post("/api/v1/logout") + def logout(request: Request, _session: Session = Depends(require_write)): + sessions.revoke(request.cookies.get(COOKIE_NAME)) + response = JSONResponse({"ok": True}) + response.delete_cookie(COOKIE_NAME, path="/") + return response + + @app.get("/api/v1/ssh-keys") + def list_ssh_keys(_session: Session = Depends(require_session)): + account = account_for_session(_session) + return {"items": ssh_key_store().list_for_user(account["id"])} + + @app.post("/api/v1/ssh-keys", status_code=201) + def create_ssh_key(body: SSHKeyBody, + _session: Session = Depends(require_write)): + account = account_for_session(_session) + return ssh_key_store().create_for_user( + account["id"], body.name, body.public_key, + ) + + @app.delete("/api/v1/ssh-keys/{key_id}") + def delete_ssh_key(key_id: int, _session: Session = Depends(require_write)): + if key_id < 1: + raise SSHKeyError("公钥不存在", 404) + account = account_for_session(_session) + if not ssh_key_store().delete_for_user(account["id"], key_id): + raise SSHKeyError("公钥不存在", 404) + return {"deleted": True} + + @app.get("/api/v1/smtp/settings") + def get_smtp_settings(_session: Session = Depends(require_admin)): + return smtp_store().public_status() + + @app.put("/api/v1/smtp/settings") + def save_smtp_settings(body: SMTPSettingsBody, + _session: Session = Depends(require_admin_write)): + settings_data = body.model_dump(exclude={"password"}) + settings_data["password"] = (body.password.get_secret_value() + if body.password is not None else "") + config = smtp_store().save(settings_data) + LOG.info("SMTP settings changed: admin=%s", _session.username) + return config.public_status() + + @app.get("/api/v1/users/pending") + def pending_users(_session: Session = Depends(require_admin)): + if not database_mode: + return {"items": []} + return {"items": state.users.list_pending_users()} + + @app.post("/api/v1/users/{user_id}/approve") + def approve_user(user_id: int, _session: Session = Depends(require_admin_write)): + if not database_mode: + raise HTTPException(status_code=409, detail="数据库用户功能不可用") + account = state.users.approve_user(user_id) + if account is None: + raise HTTPException(status_code=404, detail="用户不存在") + LOG.info("user approved: id=%s admin=%s", user_id, _session.username) + return {"approved": True} + + def public_update_settings() -> dict: + info = current_updater().settings() + return { + "repository_url": info["repository"], + "branch": info["branch"], + "token_configured": info["token_configured"], + "checkout_ready": info["checkout_ready"], + "configured": info["token_configured"] and info["checkout_ready"], + "current_version": info["current_commit"], + "active_job_id": info.get("active_job_id"), + "last_job_id": info.get("last_job_id"), + "checkout_error": info.get("checkout_error"), + } + + @app.get("/api/v1/update/settings") + def update_settings(_session: Session = Depends(require_admin)): + return public_update_settings() + + @app.put("/api/v1/update/settings") + def save_update_settings(body: UpdateSettingsBody, + _session: Session = Depends(require_admin_write)): + if body.repository_url != REPOSITORY_URL or body.branch != BRANCH: + raise UpdateError("更新仓库和分支固定为面板指定的 Gitea main 分支", 422) + service = current_updater() + if body.access_token is not None: + token = body.access_token.get_secret_value() + if token: + service.set_token(token) + if not service.settings()["token_configured"]: + raise UpdateError("请填写 Gitea 私有仓库访问令牌", 422) + LOG.info("panel update access token configured: admin=%s", _session.username) + return public_update_settings() + + @app.post("/api/v1/update/check") + def check_update(_session: Session = Depends(require_admin_write)): + result = current_updater().check() + return { + "repository_url": result["repository"], + "branch": result["branch"], + "current_version": result["current_commit"], + "latest_version": result["remote_commit"], + "update_available": result["status"] == "update_available", + } + + @app.post("/api/v1/update/apply", status_code=202) + def apply_update(body: UpdateApplyBody, _session: Session = Depends(require_admin_write)): + with import_lock, reinstall_lock, rescue_lock, rescue_import_lock: + if (pending_templates or pending_reinstalls or pending_rescues + or pending_rescue_imports): + raise UpdateError("镜像导入或虚拟机任务正在执行,请等待完成后再更新面板", 409) + try: + unit = subprocess.run( + ["/usr/bin/systemctl", "is-active", "virsh-panel-update.service"], + capture_output=True, text=True, timeout=5, check=False, + ) + except (OSError, subprocess.TimeoutExpired): + unit = None + if unit is not None and unit.stdout.strip() in { + "activating", "active", "deactivating", "reloading", + }: + raise UpdateError("独立更新服务仍在运行,请等待其完全结束后再提交", 409) + service = current_updater() + job = service.create_job( + expected_current_commit=body.expected_current_commit, + expected_remote_commit=body.expected_remote_commit, + ) + try: + # The web service has a read-only code tree. A separate one-shot + # unit performs the Git update and restarts this service. + trigger = subprocess.run( + ["/usr/bin/systemctl", "--no-block", "start", "virsh-panel-update.service"], + capture_output=True, text=True, timeout=10, check=False, + ) + except (OSError, subprocess.TimeoutExpired): + trigger = None + if trigger is None or trigger.returncode != 0: + service.fail_job(job["job_id"], + "无法启动独立更新服务;请检查 virsh-panel-update.service 是否已安装") + raise UpdateError("无法启动独立更新服务;请检查 systemd 配置", 503) + LOG.info("panel update queued: job=%s admin=%s", job["job_id"], _session.username) + return {"job_id": job["job_id"], "status": "queued"} + + @app.get("/api/v1/update/jobs/{job_id}") + def update_job(job_id: str, _session: Session = Depends(require_admin)): + job = current_updater().get_job(job_id) + if job is None: + raise UpdateError("更新任务不存在", 404) + return job + + @app.get("/api/v1/host") + def host(_session: Session = Depends(require_admin)): + return _public_host(manager.current()) + + @app.post("/api/v1/host/scan") + def scan_host(body: HostScanBody, _session: Session = Depends(require_admin_write)): + return manager.scan(body.host, body.port) + + @app.post("/api/v1/host/unlock") + def unlock_host(body: UnlockBody, request: Request, _session: Session = Depends(require_admin_write)): + peer = _peer(request) + if not unlock_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="私钥口令尝试过多,请稍后再试") + try: + profile = manager.unlock_current(body.passphrase) + except RemoteHostError as exc: + if exc.status == 400: + unlock_limiter.failed(peer) + raise + unlock_limiter.succeeded(peer) + LOG.info("remote host SSH key unlocked: host=%s admin=%s", profile.get("host"), _session.username) + return _public_host(profile) + + @app.post("/api/v1/host/test") + def test_host(body: HostBody, _session: Session = Depends(require_admin_write)): + staged = manager.stage(body.profile(), confirmed_fingerprint=body.confirmed_fingerprint) + try: + result = manager.test(staged) + resources, resource_warning = validate_staged_libvirt(staged, body) + return { + **result, + "resources": resources, + "warnings": [resource_warning] if resource_warning else [], + } + finally: + manager.abort(staged) + + @app.put("/api/v1/host") + def save_host(body: HostBody, _session: Session = Depends(require_admin_write)): + # A running reinstall uses the saved SSH host identity and paths. Do + # not replace them while its libvirt operation is in flight. + with reinstall_lock, rescue_lock, rescue_import_lock: + forbid_long_job_during_update() + if (pending_reinstalls or pending_rescues or pending_rescue_imports + or (data_store is not None and data_store.list("vm_rescue"))): + raise VMError("请先完成救援或重装任务并退出救援模式,再修改宿主机配置", 409) + if any( + job.get("status") == "succeeded" and "generated_password" in job + for job in reinstall_jobs.values()): + raise VMError("请先完成重装任务并确认保存自动生成的密码,再修改宿主机配置", 409) + staged = manager.stage(body.profile(), confirmed_fingerprint=body.confirmed_fingerprint) + committed = False + try: + manager.test(staged) + _resources, resource_warning = validate_staged_libvirt(staged, body, ensure_paths=True) + profile = manager.commit(staged) + committed = True + finally: + if not committed: + manager.abort(staged) + LOG.info("remote host configured: host=%s port=%s admin=%s", body.host, body.port, _session.username) + return { + **_public_host(profile), + "warnings": [resource_warning] if resource_warning else [], + } + + @app.get("/api/v1/resources") + def resources(_session: Session = Depends(require_approved)): + profile = current_profile() + return { + **new_service(profile).resources(), + "public_pool_cidr": profile.get("public_pool_cidr", ""), + "public_pool_enabled": bool(profile.get("public_pool_cidr")), + "public_vm_prefix": profile.get("public_vm_prefix"), + } + + @app.get("/api/v1/vm-templates") + def list_templates(_session: Session = Depends(require_approved)): + profile = current_profile() + return {"templates": templates.list(template_scope(profile))} + + def run_template_import(job_id: str, profile: dict, scope: str, + body: ImportTemplateBody, template_id: str) -> None: + image_path = None + volume_name = template_volume_name(template_id) + uploaded = False + try: + image_path, virtual_size = download_verified_image( + body.url, body.sha256.lower(), settings.data_dir) + result = new_service(profile).import_template(image_path, volume_name, virtual_size) + uploaded = True + record = { + "id": template_id, + "name": body.name, + "os_family": "AlmaLinux", + "os_version": image_version_for(body.url), + "sha256": body.sha256.lower(), + "volume_name": volume_name, + "virtual_size": virtual_size, + "image_bytes": result["image_bytes"], + } + templates.add(scope, record) + with import_lock: + import_jobs[job_id] = {"scope": scope, "status": "completed", + "template": record} + save_job("import_job", job_id, import_jobs[job_id]) + except Exception as exc: + if isinstance(exc, (TemplateError, VMError)): + error = str(exc) + else: + LOG.exception("Cloud template import failed: job=%s", job_id) + error = "云镜像导入失败,请查看面板日志" + if uploaded: + error += f";宿主机模板卷 {volume_name} 可能需要人工检查" + with import_lock: + import_jobs[job_id] = {"scope": scope, "status": "failed", "error": error} + save_job("import_job", job_id, import_jobs[job_id]) + finally: + if image_path is not None: + image_path.unlink(missing_ok=True) + with import_lock: + pending_templates.discard((scope, template_id)) + + @app.post("/api/v1/vm-templates/import", status_code=202) + def import_template(body: ImportTemplateBody, _session: Session = Depends(require_admin_write)): + profile = current_profile() + version = image_version_for(body.url) + name = validate_template_name(body.name) + body = body.model_copy(update={"name": name}) + if not all(char in "0123456789abcdefABCDEF" for char in body.sha256): + raise TemplateError("SHA-256 校验值必须是十六进制") + scope = template_scope(profile) + template_id = template_id_for(scope, body.sha256.lower(), version) + with import_lock: + forbid_long_job_during_update() + existing_templates = templates.list(scope) + if any(row["id"] == template_id for row in existing_templates): + raise TemplateError("此云镜像已经导入", 409) + if any(row["name"].casefold() == name.casefold() + for row in existing_templates): + raise TemplateError("当前宿主机已有同名云镜像模板", 409) + if (scope, template_id) in pending_templates: + raise TemplateError("该云镜像正在导入", 409) + if pending_templates: + raise TemplateError("已有云镜像正在导入,请等待完成后再提交", 409) + job_id = str(uuid.uuid4()) + pending_templates.add((scope, template_id)) + import_jobs[job_id] = {"scope": scope, "status": "running"} + save_job("import_job", job_id, import_jobs[job_id]) + try: + import_executor.submit(run_template_import, job_id, profile, + scope, body, template_id) + except RuntimeError as exc: + pending_templates.discard((scope, template_id)) + import_jobs.pop(job_id, None) + delete_job("import_job", job_id) + raise TemplateError("面板正在停止,无法开始导入任务", 503) from exc + LOG.info("cloud template import queued: job=%s admin=%s", job_id, _session.username) + return {"job_id": job_id, "status": "running"} + + @app.patch("/api/v1/vm-templates/{template_id}") + def rename_template(template_id: str, body: RenameTemplateBody, + _session: Session = Depends(require_admin_write)): + scope = template_scope(current_profile()) + with import_lock: + if pending_templates: + raise TemplateError("云镜像正在导入,请稍后修改模板名称", 409) + return {"template": templates.rename(scope, template_id, body.name)} + + @app.get("/api/v1/vm-templates/import-jobs/{job_id}") + def import_job(job_id: str, _session: Session = Depends(require_admin)): + scope = template_scope(current_profile()) + with import_lock: + job = import_jobs.get(job_id) + if job is None or job["scope"] != scope: + raise TemplateError("导入任务不存在", 404) + return {key: value for key, value in job.items() if key != "scope"} + + @app.get("/api/v1/rescue-templates") + def list_rescue_templates(_session: Session = Depends(require_approved)): + return {"templates": rescue_catalog.list(rescue_scope(current_profile()))} + + def run_rescue_import(job_id: str, profile: dict, scope: str, + record: dict, image_path: Path) -> None: + uploaded = False + cataloged = False + try: + with rescue_import_lock: + rescue_import_jobs[job_id]["status"] = "running" + rescue_import_jobs[job_id]["phase"] = "正在传输 ISO 到宿主机" + save_job("rescue_import_job", job_id, rescue_import_jobs[job_id]) + new_service(profile).import_rescue_iso(image_path, record["volume_name"]) + uploaded = True + rescue_catalog.add(scope, record) + cataloged = True + with rescue_import_lock: + rescue_import_jobs[job_id] = { + "scope": scope, "status": "completed", "phase": "救援模版已导入", + "template": record, + } + save_job("rescue_import_job", job_id, rescue_import_jobs[job_id]) + except Exception as exc: + if isinstance(exc, (TemplateError, VMError)): + error = str(exc) + else: + LOG.exception("Rescue ISO import failed: job=%s", job_id) + error = "救援 ISO 导入失败,请查看面板日志" + if cataloged: + try: + rescue_catalog.delete(scope, record["id"]) + except Exception: + LOG.exception("Could not clean failed rescue catalog entry: job=%s", job_id) + error += ";数据库中可能留有救援模版记录,请管理员检查" + if uploaded: + try: + new_service(profile).delete_rescue_iso(record["volume_name"]) + except Exception: + LOG.exception("Could not clean failed rescue ISO import: job=%s", job_id) + error += ";宿主机上可能留有救援 ISO 卷,请管理员检查" + with rescue_import_lock: + rescue_import_jobs[job_id] = { + "scope": scope, "status": "failed", "phase": "导入失败", "error": error, + } + try: + save_job("rescue_import_job", job_id, rescue_import_jobs[job_id]) + except DatabaseError: + LOG.exception("Could not persist rescue import failure: job=%s", job_id) + finally: + image_path.unlink(missing_ok=True) + with rescue_import_lock: + pending_rescue_imports.discard(scope) + + @app.post("/api/v1/rescue-templates", status_code=202) + async def upload_rescue_template( + request: Request, + name: str = Query(min_length=1, max_length=64), + _session: Session = Depends(require_admin_write), + ): + name = validate_template_name(name) + profile = current_profile() + scope = rescue_scope(profile) + with rescue_import_lock: + forbid_long_job_during_update() + if scope in pending_rescue_imports: + raise TemplateError("已有救援 ISO 正在导入,请等待完成", 409) + if any(row["name"].casefold() == name.casefold() + for row in rescue_catalog.list(scope)): + raise TemplateError("当前宿主机已有同名救援模版", 409) + pending_rescue_imports.add(scope) + image_path: Path | None = None + handed_off = False + try: + declared_size = request.headers.get("content-length") + if declared_size is not None: + try: + if int(declared_size) > MAX_RESCUE_ISO_BYTES: + raise TemplateError("救援 ISO 超过 8 GiB 限制", 413) + except ValueError as exc: + raise TemplateError("上传长度无效", 400) from exc + fd, raw_path = tempfile.mkstemp(prefix=".rescue-upload-", suffix=".iso", + dir=settings.data_dir) + image_path = Path(raw_path) + os.fchmod(fd, 0o600) + checksum = hashlib.sha256() + size = 0 + with os.fdopen(fd, "wb") as output: + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_RESCUE_ISO_BYTES: + raise TemplateError("救援 ISO 超过 8 GiB 限制", 413) + output.write(chunk) + checksum.update(chunk) + output.flush() + os.fsync(output.fileno()) + if internal_mode: + validation = request.scope.get("engine_upload_validation", {}) + if not validation.get("complete") or not validation.get("valid"): + raise HTTPException(status_code=401, detail="救援 ISO 摘要与签名不匹配") + verify_bootable_iso(image_path) + template_id = uuid.uuid4().hex + record = { + "id": template_id, "name": name, + "volume_name": rescue_volume_name(template_id), + "size_bytes": size, "sha256": checksum.hexdigest(), + } + job_id = str(uuid.uuid4()) + with rescue_import_lock: + rescue_import_jobs[job_id] = { + "scope": scope, "status": "queued", "phase": "等待传输到宿主机", + } + save_job("rescue_import_job", job_id, rescue_import_jobs[job_id]) + try: + rescue_import_executor.submit( + run_rescue_import, job_id, profile, scope, record, image_path, + ) + except RuntimeError as exc: + rescue_import_jobs.pop(job_id, None) + delete_job("rescue_import_job", job_id) + raise TemplateError("面板正在停止,无法导入救援 ISO", 503) from exc + LOG.info("rescue ISO import queued: job=%s admin=%s", job_id, _session.username) + handed_off = True # The worker now owns and removes the temporary file. + return {"job_id": job_id, "status": "queued"} + finally: + if not handed_off: + if image_path is not None: + image_path.unlink(missing_ok=True) + with rescue_import_lock: + pending_rescue_imports.discard(scope) + + @app.get("/api/v1/rescue-templates/import-jobs/{job_id}") + def rescue_import_job(job_id: str, _session: Session = Depends(require_admin)): + scope = rescue_scope(current_profile()) + with rescue_import_lock: + job = rescue_import_jobs.get(job_id) + if job is None or job["scope"] != scope: + raise TemplateError("救援模版导入任务不存在", 404) + return {key: value for key, value in job.items() if key != "scope"} + + @app.delete("/api/v1/rescue-templates/{template_id}") + def delete_rescue_template(template_id: str, + _session: Session = Depends(require_admin_write)): + profile = current_profile() + scope = rescue_scope(profile) + with rescue_lock, rescue_import_lock: + forbid_long_job_during_update() + if scope in pending_rescue_imports: + raise TemplateError("救援 ISO 正在导入,请稍后删除", 409) + record = rescue_catalog.get(scope, template_id) + states = (data_store.list("vm_rescue") if data_store is not None + else test_rescue_states.copy()) + for raw in states.values(): + try: + state_record = json.loads(raw) + except (TypeError, ValueError) as exc: + raise DatabaseError("虚拟机救援记录损坏") from exc + if not isinstance(state_record, dict): + raise DatabaseError("虚拟机救援记录损坏") + if state_record.get("volume_name") == record["volume_name"]: + raise TemplateError("此救援模版正被虚拟机使用,须先退出救援模式", 409) + try: + new_service(profile).delete_rescue_iso(record["volume_name"]) + except VMError as exc: + if exc.status != 404: + raise + rescue_catalog.delete(scope, template_id) + LOG.info("rescue ISO deleted: id=%s admin=%s", template_id, _session.username) + return {"deleted": True} + + @app.get("/api/v1/vms") + def list_vms(_session: Session = Depends(require_approved)): + profile = current_profile() + vms = new_service(profile).list_vms() + if database_mode: + account = account_for_session(_session) + if not account["admin"]: + owned_ids = state.users.list_owned_vm_ids(host_scope(profile), account["id"]) + vms = [vm for vm in vms if vm["uuid"] in owned_ids] + records = (data_store.list("vm_credential") if data_store is not None + else test_credentials.copy()) + return {"items": [decorate_vm( + vm, parse_credential(records.get(credential_key(profile, vm["uuid"]))), profile, + ) for vm in vms]} + + @app.get("/api/v1/vms/{vm_id}") + def get_vm(vm_id: str, _session: Session = Depends(require_approved)): + profile = current_profile() + require_vm_access(_session, profile, vm_id) + vm = new_service(profile).get_vm(vm_id) + return decorate_vm(vm, get_credential(profile, vm["uuid"]), profile) + + @app.post("/api/v1/vms/{vm_id}/credential") + def reveal_vm_credential(vm_id: str, _session: Session = Depends(require_approved_write)): + profile = current_profile() + require_vm_access(_session, profile, vm_id) + vm = new_service(profile).get_vm(vm_id) + credential = get_credential(profile, vm["uuid"]) + decorated = decorate_vm(vm, credential, profile) + LOG.info("vm credential viewed: uuid=%s admin=%s", vm["uuid"], _session.username) + return { + "login_name": decorated["login_name"], + "auth_mode": decorated["auth_mode"], + "password": credential["password"] if decorated["password_available"] else None, + } + + @app.get("/api/v1/vms/{vm_id}/metrics") + def get_vm_metrics( + vm_id: str, + range_: Literal["1h", "24h", "7d", "30d"] = Query("1h", alias="range"), + _session: Session = Depends(require_approved), + ): + try: + canonical_id = str(uuid.UUID(vm_id)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效", 400) from exc + profile = current_profile() + require_vm_access(_session, profile, canonical_id) + # Never reveal another host's retained samples for a reused UUID. + new_service(profile).get_vm(canonical_id) + backend = metric_store if metric_store is not None else data_store + if backend is None: + raise HTTPException(status_code=503, detail="指标数据库尚未就绪") + now = int(time.time()) + window = RANGES[range_] + interval = query_interval_seconds(window) + since = max(now - window, now - RETENTION_SECONDS) + try: + scope = host_scope(profile) + except (KeyError, ValueError, TypeError) as exc: + raise HTTPException(status_code=409, detail="宿主机身份信息不完整") from exc + points = backend.query_metric_samples( + scope, canonical_id, since=since, until=now, + interval_seconds=interval, limit=MAX_QUERY_POINTS, + ) + return {"vm_id": canonical_id, "range": range_, + "interval_seconds": interval, "points": points} + + @app.post("/api/v1/vms", status_code=201) + def create_vm(body: CreateISOBody | CreateCloudBody, + _session: Session = Depends(require_approved_write)): + # Keep the update submission lock until libvirt has finished creating + # the VM. Otherwise an update can restart the web process mid-create. + with reinstall_lock: + forbid_long_job_during_update() + profile = current_profile() + account = account_for_session(_session) + owner_id = account["id"] if database_mode and (internal_mode or not account["admin"]) else None + if isinstance(body, CreateCloudBody): + public_key = body.guest_ssh_public_key.strip() + root_password = (body.root_password.get_secret_value() + if body.root_password is not None else "") + if body.guest_ssh_key_id is not None: + if public_key: + raise HTTPException( + status_code=422, + detail="已保存公钥和手动公钥只能选择一种", + ) + saved_key = ssh_key_store().get_for_user( + account["id"], body.guest_ssh_key_id, + ) + if saved_key is None: + raise SSHKeyError("公钥不存在", 404) + public_key = saved_key["public_key"] + # A cloud VM always has a recoverable initial root password, + # even when a saved or one-off SSH key was selected. + if not root_password: + root_password = generate_root_password() + password_hash = None + if root_password: + try: + password_hash = hash_root_password(root_password) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + auto_public_ip = bool(profile.get("public_pool_cidr")) + if auto_public_ip and (body.public_ip_cidr or body.gateway or body.dns_servers): + raise HTTPException( + status_code=422, + detail="宿主机已配置公网地址池,创建时不能手动指定 IP、网关或 DNS", + ) + if not auto_public_ip and not ( + body.public_ip_cidr and body.gateway and body.dns_servers + ): + raise HTTPException( + status_code=422, + detail="宿主机尚未配置公网地址池,请手动填写 IP、网关和 DNS", + ) + record = templates.get(template_scope(profile), body.template_id) + spec = body.model_dump(exclude_none=True, exclude={ + "source", "template_id", "root_password", "guest_ssh_key_id", + }) + spec["os_name"] = record.get("name") + spec["guest_ssh_public_key"] = public_key + if password_hash is not None: + spec["root_password_hash"] = password_hash + requested_uuid = actor()["vm_uuid"] if internal_mode else str(uuid.uuid4()) + spec["vm_uuid"] = requested_uuid + service = new_service(profile) + allocated_ip = "" + owner_assigned = False + try: + if auto_public_ip: + allocated_ip = allocate_public_ip( + profile, service, requested_uuid, + ) + spec["public_ip_cidr"] = allocated_ip + spec["gateway"] = profile["public_gateway"] + spec["dns_servers"] = list(profile["public_dns_servers"]) + else: + claim_explicit_public_ip(profile, body.public_ip_cidr, requested_uuid) + allocated_ip = body.public_ip_cidr + if owner_id is not None: + state.users.assign_vm(host_scope(profile), requested_uuid, owner_id) + owner_assigned = True + save_credential(profile, requested_uuid, + ("ssh_key_password" if public_key and root_password + else "ssh_key" if public_key else "password"), + f"panel-seed-{requested_uuid}.iso", + root_password or None) + vm = service.create_cloud_vm(spec, record["volume_name"]) + except Exception as exc: + # An incomplete libvirt rollback may have left the guest + # behind. Keep its credential in that exceptional case so + # the operator can still recover access if it exists. + rollback_incomplete = (internal_mode or (isinstance(exc, VMError) + and "回滚不完整" in str(exc))) + if not rollback_incomplete: + try: + delete_credential(profile, requested_uuid) + except DatabaseError: + LOG.exception("Could not remove unused VM credential for %s", requested_uuid) + if owner_assigned: + try: + state.users.delete_vm_owner(host_scope(profile), requested_uuid) + except DatabaseError: + LOG.exception("Could not remove unused VM owner for %s", requested_uuid) + if allocated_ip: + try: + release_public_ip_claim(profile, allocated_ip, requested_uuid) + except DatabaseError: + LOG.exception("Could not release unused public IP claim for %s", requested_uuid) + raise + vm = verified_created_vm(profile, vm, requested_uuid) + else: + spec = body.model_dump(exclude_none=True, exclude={"source"}) + if database_mode: + requested_uuid = actor()["vm_uuid"] if internal_mode else str(uuid.uuid4()) + spec["vm_uuid"] = requested_uuid + if owner_id is not None: + state.users.assign_vm(host_scope(profile), requested_uuid, owner_id) + try: + vm = new_service(profile).create_vm(spec) + except Exception as exc: + rollback_incomplete = (internal_mode or (isinstance(exc, VMError) + and "回滚不完整" in str(exc))) + if owner_id is not None and not rollback_incomplete: + state.users.delete_vm_owner(host_scope(profile), requested_uuid) + raise + if database_mode: + vm = verified_created_vm(profile, vm, requested_uuid) + LOG.info("vm created: uuid=%s admin=%s", vm.get("uuid"), _session.username) + credential = get_credential(profile, vm["uuid"]) if isinstance(body, CreateCloudBody) else None + return decorate_vm(vm, credential, profile) + + def run_reinstall( + job_id: str, profile: dict, scope: str, vm_id: str, + template_volume_name: str, template_name: str | None, ssh_public_key: str, + root_password_hash: str | None, generated_password: str | None, + credential_password: str | None, + ) -> None: + vm_reinstalled = False + def report_progress(phase: str) -> None: + if not isinstance(phase, str): + return + with reinstall_lock: + job = reinstall_jobs.get(job_id) + if job is not None and job["status"] == "running": + job["phase"] = phase[:200] + save_job("reinstall_job", job_id, job) + + try: + with reinstall_lock: + reinstall_jobs[job_id]["status"] = "running" + reinstall_jobs[job_id]["phase"] = "正在检查虚拟机" + save_job("reinstall_job", job_id, reinstall_jobs[job_id]) + result = new_service(profile).reinstall_cloud_vm( + vm_id, template_volume_name, + os_name=template_name, + ssh_public_key=ssh_public_key, + root_password_hash=root_password_hash, + progress=report_progress, + ) + vm_reinstalled = True + save_credential(profile, vm_id, + ("ssh_key_password" if ssh_public_key and credential_password + else "ssh_key" if ssh_public_key else "password"), + result["credential_generation"], + credential_password) + with reinstall_lock: + job = reinstall_jobs[job_id] + job["status"] = "succeeded" + job["phase"] = "重装完成" + if isinstance(result, dict) and result.get("warning"): + job["warning"] = str(result["warning"]) + if generated_password is not None: + # DatabaseStore encrypts this one-time password. Keep it + # until the operator explicitly acknowledges saving it. + job["generated_password"] = generated_password + save_job("reinstall_job", job_id, job) + LOG.info("vm reinstall succeeded: job=%s uuid=%s", job_id, vm_id) + except Exception as exc: + if isinstance(exc, (VMError, TemplateError, ValueError)): + error = str(exc) + else: + LOG.exception("VM reinstall failed: job=%s uuid=%s", job_id, vm_id) + error = "重装系统失败,请查看面板日志" + with reinstall_lock: + job = reinstall_jobs[job_id] + if vm_reinstalled: + job["status"] = "succeeded" + job["phase"] = "重装已完成,但凭据或任务记录保存失败" + job["warning"] = "新系统已启动,但面板无法确认初始密码已保存;请立即保存结果页显示的密码并检查数据库" + if generated_password is not None: + job["generated_password"] = generated_password + else: + job["status"] = "failed" + job["phase"] = "重装失败" + job["error"] = error + try: + save_job("reinstall_job", job_id, job) + except DatabaseError: + LOG.exception("Could not persist reinstall status: job=%s", job_id) + if not vm_reinstalled: + LOG.warning("vm reinstall failed: job=%s uuid=%s", job_id, vm_id) + finally: + with reinstall_lock: + pending_reinstalls.discard((scope, vm_id)) + + @app.post("/api/v1/vms/{vm_id}/reinstall", status_code=202) + def reinstall_vm(vm_id: str, body: ReinstallBody, + _session: Session = Depends(require_approved_write)): + ssh_public_key = body.ssh_public_key.strip() + supplied_password = (body.root_password.get_secret_value() + if body.root_password is not None else "") + if body.ssh_key_id is not None: + if ssh_public_key: + raise HTTPException( + status_code=422, + detail="已保存公钥和手动公钥只能选择一种", + ) + account = account_for_session(_session) + saved_key = ssh_key_store().get_for_user(account["id"], body.ssh_key_id) + if saved_key is None: + raise SSHKeyError("公钥不存在", 404) + ssh_public_key = saved_key["public_key"] + generated_password = None + if not supplied_password and not ssh_public_key: + generated_password = generate_root_password() + supplied_password = generated_password + try: + if ssh_public_key: + ssh_public_key, _unused_hash = _validate_guest_auth(ssh_public_key, None) + root_password_hash = (hash_root_password(supplied_password) + if supplied_password else None) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + + with reinstall_lock, rescue_lock: + forbid_long_job_during_update() + profile = current_profile() + require_vm_access(_session, profile, vm_id) + canonical_id = str(uuid.UUID(vm_id)) + service = new_service(profile) + rescue_record = current_rescue_state(profile, canonical_id, service) + rescue_vm = service.get_vm(canonical_id) + if ((host_scope(profile), canonical_id) in pending_rescues + or rescue_record is not None + or rescue_vm.get("rescue_mode") + or rescue_vm.get("rescue_staged")): + raise VMError("虚拟机处于救援模式或救援任务中,请先退出救援模式", 409) + scope = template_scope(profile) + record = templates.get(scope, body.template_id) + vm = service.get_vm(vm_id) + if not vm.get("managed") or not vm.get("public_ip_cidr"): + raise VMError("只有面板创建的公网云镜像虚拟机支持自动重装", 409) + if body.confirmation_name != vm["name"]: + raise HTTPException(status_code=422, detail="确认名称与虚拟机名称不一致") + normalized_id = vm["uuid"] + key = (scope, normalized_id) + if key in pending_reinstalls: + raise VMError("该虚拟机正在重装系统", 409) + job_id = str(uuid.uuid4()) + reinstall_jobs[job_id] = { + "owner": _session.username, + "scope": scope, + "status": "queued", + "phase": "等待重装任务开始", + "vm_id": normalized_id, + "template_id": record["id"], + } + save_job("reinstall_job", job_id, reinstall_jobs[job_id]) + pending_reinstalls.add(key) + try: + reinstall_executor.submit( + run_reinstall, job_id, profile, scope, normalized_id, + record["volume_name"], record.get("name"), ssh_public_key, root_password_hash, + generated_password, supplied_password or None, + ) + except RuntimeError as exc: + pending_reinstalls.discard(key) + reinstall_jobs.pop(job_id, None) + delete_job("reinstall_job", job_id) + raise VMError("面板正在停止,无法开始重装任务", 503) from exc + LOG.info("vm reinstall queued: job=%s uuid=%s admin=%s", + job_id, normalized_id, _session.username) + return {"job_id": job_id, "status": "queued"} + + @app.get("/api/v1/reinstall-jobs/{job_id}") + def reinstall_job(job_id: str, _session: Session = Depends(require_approved_write)): + scope = template_scope(current_profile()) + with reinstall_lock: + job = reinstall_jobs.get(job_id) + if (job is None or job["scope"] != scope + or job["owner"] != _session.username): + raise VMError("重装任务不存在", 404) + result = {key: value for key, value in job.items() + if key not in ("scope", "owner", "generated_password")} + if job["status"] == "succeeded" and "generated_password" in job: + result["generated_password"] = job["generated_password"] + return result + + @app.post("/api/v1/reinstall-jobs/{job_id}/ack-password") + def acknowledge_reinstall_password(job_id: str, + _session: Session = Depends(require_approved_write)): + scope = template_scope(current_profile()) + with reinstall_lock: + job = reinstall_jobs.get(job_id) + if (job is None or job["scope"] != scope + or job["owner"] != _session.username): + raise VMError("重装任务不存在", 404) + if job["status"] != "succeeded": + raise VMError("重装任务尚未成功,不能确认密码", 409) + job.pop("generated_password", None) + save_job("reinstall_job", job_id, job) + return {"acknowledged": True} + + def run_rescue_job(job_id: str, profile: dict, vm_id: str, + operation: Literal["enter", "exit", "force"]) -> None: + vm_scope = host_scope(profile) + key = (vm_scope, vm_id) + completed = False + try: + with rescue_lock: + job = rescue_jobs[job_id] + job["status"] = "running" + job["phase"] = ( + "正在预挂载救援 ISO 并等待正常关机" if operation == "enter" + else "正在强制断电并从救援 ISO 冷启动" if operation == "force" + else "正在正常关机并恢复原系统启动配置" + ) + save_job("rescue_job", job_id, job) + state_record = load_rescue_state(profile, vm_id) + if state_record is None: + raise VMError("救援恢复记录丢失,已停止操作", 409) + state_record["status"] = "exiting" if operation == "exit" else "running" + save_rescue_state(profile, vm_id, state_record) + service = new_service(profile) + if operation == "enter": + result = service.enter_rescue_vm(vm_id, state_record["volume_name"], + state_record["original_xml"]) + elif operation == "force": + result = service.force_start_staged_rescue_vm( + vm_id, state_record["original_xml"]) + else: + result = service.exit_rescue_vm(vm_id, state_record["original_xml"]) + completed = True + staged = (operation == "enter" and isinstance(result, dict) + and result.get("pending_manual_restart") is True) + with rescue_lock: + if operation in {"enter", "force"}: + state_record["status"] = "staged" if staged else "active" + save_rescue_state(profile, vm_id, state_record) + else: + delete_rescue_state(profile, vm_id) + job = rescue_jobs[job_id] + job["status"] = "completed" + job["phase"] = ("救援 ISO 已预挂载,等待手动强制断电后开机" if staged + else "救援系统已启动" if operation in {"enter", "force"} + else "已退出救援模式,原系统已启动") + if staged: + job["pending_manual_restart"] = True + if isinstance(result, dict) and result.get("warning"): + job["warning"] = str(result["warning"]) + save_job("rescue_job", job_id, job) + LOG.info("vm rescue %s succeeded: job=%s uuid=%s", operation, job_id, vm_id) + except Exception as exc: + if isinstance(exc, (VMError, TemplateError)): + error = str(exc) + else: + LOG.exception("VM rescue %s failed: job=%s uuid=%s", operation, job_id, vm_id) + error = "紧急救援操作失败,请查看面板和宿主机日志" + with rescue_lock: + try: + state_record = load_rescue_state(profile, vm_id) + if state_record is not None: + # If the original inactive definition survived, the + # failed job cannot strand an otherwise normal VM in + # a database-only "rescue" state. + service = new_service(profile) + actual_vm = service.get_vm(vm_id) + if (not actual_vm.get("rescue_mode") + and rescue_xml_matches( + service.prepare_rescue_vm( + vm_id, state_record["volume_name"]), + state_record["original_xml"], + )): + delete_rescue_state(profile, vm_id) + else: + state_record["status"] = "failed" + save_rescue_state(profile, vm_id, state_record) + except (DatabaseError, VMError, TemplateError): + LOG.exception("Could not save rescue recovery state: job=%s", job_id) + job = rescue_jobs[job_id] + job["status"] = "failed" + job["phase"] = "救援操作失败" + if "正常关机超时" in error or "无法请求虚拟机正常关机" in error: + job["error"] = error + else: + job["error"] = error + ";请确认虚拟机实际运行状态,必要时联系管理员" + if completed: + job["error"] = "虚拟机操作已完成,但数据库状态保存失败;请管理员检查救援记录" + try: + save_job("rescue_job", job_id, job) + except DatabaseError: + LOG.exception("Could not persist rescue job failure: job=%s", job_id) + finally: + with rescue_lock: + pending_rescues.discard(key) + + @app.get("/api/v1/vms/{vm_id}/rescue") + def get_vm_rescue(vm_id: str, _session: Session = Depends(require_approved)): + profile = current_profile() + canonical_id = require_vm_access(_session, profile, vm_id) + with rescue_lock: + service = new_service(profile) + vm = service.get_vm(canonical_id) + record = current_rescue_state(profile, vm["uuid"], service) + staged = bool(vm.get("rescue_staged")) + active = bool(vm.get("rescue_mode")) and not staged + if (record is not None + and (host_scope(profile), vm["uuid"]) not in pending_rescues): + if staged and record["status"] in {"queued", "running", "failed"}: + record["status"] = "staged" + save_rescue_state(profile, vm["uuid"], record) + elif active and record["status"] in {"queued", "running", "staged"}: + record["status"] = "active" + save_rescue_state(profile, vm["uuid"], record) + template_name = None + template_id = record["template_id"] if record is not None else None + if record is not None: + try: + template_name = rescue_catalog.get( + rescue_scope(profile), record["template_id"])["name"] + except TemplateError: + pass + return { + "active": active, + "staged": staged, + "power_state": vm.get("state", "unknown"), + "template_id": template_id, + "template_name": template_name, + "status": record["status"] if record is not None else None, + "job_id": record.get("job_id") if record is not None else None, + "can_exit": (active or staged) and record is not None, + } + + @app.post("/api/v1/vms/{vm_id}/rescue", status_code=202) + def enter_vm_rescue(vm_id: str, body: EnterRescueBody, + _session: Session = Depends(require_approved_write)): + with reinstall_lock, rescue_lock: + forbid_long_job_during_update() + profile = current_profile() + canonical_id = require_vm_access(_session, profile, vm_id) + vm_scope = host_scope(profile) + key = (vm_scope, canonical_id) + if key in pending_rescues or (template_scope(profile), canonical_id) in pending_reinstalls: + raise VMError("该虚拟机已有救援或重装任务,暂时不能重复操作", 409) + service = new_service(profile) + vm = service.get_vm(canonical_id) + if body.confirmation_name != vm["name"]: + raise VMError("确认名称与虚拟机名称不一致", 422) + if vm.get("rescue_mode") or vm.get("rescue_staged"): + raise VMError("虚拟机已预挂载救援 ISO 或处于救援模式,请先退出", 409) + record = rescue_catalog.get(rescue_scope(profile), body.template_id) + original_xml = service.prepare_rescue_vm(canonical_id, record["volume_name"]) + prior = load_rescue_state(profile, canonical_id) + if prior is not None: + if not rescue_xml_matches(prior["original_xml"], original_xml): + raise VMError("虚拟机仍有未完成的救援记录,请管理员检查后再操作", 409) + delete_rescue_state(profile, canonical_id) + job_id = str(uuid.uuid4()) + state_record = { + "template_id": record["id"], "volume_name": record["volume_name"], + "original_xml": original_xml, "status": "queued", "job_id": job_id, + } + save_rescue_state(profile, canonical_id, state_record) + rescue_jobs[job_id] = { + "scope": vm_scope, "owner": _session.username, + "vm_id": canonical_id, "operation": "enter", + "status": "queued", "phase": "等待救援任务开始", + } + try: + save_job("rescue_job", job_id, rescue_jobs[job_id]) + pending_rescues.add(key) + rescue_executor.submit(run_rescue_job, job_id, profile, canonical_id, "enter") + except Exception: + pending_rescues.discard(key) + rescue_jobs.pop(job_id, None) + delete_job("rescue_job", job_id) + delete_rescue_state(profile, canonical_id) + raise + LOG.info("vm rescue enter queued: job=%s uuid=%s user=%s", + job_id, canonical_id, _session.username) + return {"job_id": job_id, "status": "queued"} + + @app.post("/api/v1/vms/{vm_id}/rescue/force-start", status_code=202) + def force_start_vm_rescue(vm_id: str, body: ForceRescueBody, + _session: Session = Depends(require_approved_write)): + """Explicit, confirmed power cycle into an already staged rescue ISO.""" + with reinstall_lock, rescue_lock: + forbid_long_job_during_update() + profile = current_profile() + canonical_id = require_vm_access(_session, profile, vm_id) + vm_scope = host_scope(profile) + key = (vm_scope, canonical_id) + if key in pending_rescues or (template_scope(profile), canonical_id) in pending_reinstalls: + raise VMError("该虚拟机已有救援或重装任务,请等待完成", 409) + record = load_rescue_state(profile, canonical_id) + if record is None: + raise VMError("缺少原始启动配置备份,不能安全强制重启进入救援", 409) + vm = new_service(profile).get_vm(canonical_id) + if body.confirmation_name != vm["name"]: + raise VMError("确认名称与虚拟机名称不一致", 422) + if not vm.get("rescue_staged"): + raise VMError("救援 ISO 尚未预挂载,或虚拟机已经进入救援模式", 409) + job_id = str(uuid.uuid4()) + rescue_jobs[job_id] = { + "scope": vm_scope, "owner": _session.username, + "vm_id": canonical_id, "operation": "force", + "status": "queued", "phase": "等待手动确认的救援冷启动", + } + previous_status = record["status"] + previous_job_id = record.get("job_id") + try: + save_job("rescue_job", job_id, rescue_jobs[job_id]) + record["status"] = "queued" + record["job_id"] = job_id + save_rescue_state(profile, canonical_id, record) + pending_rescues.add(key) + rescue_executor.submit(run_rescue_job, job_id, profile, canonical_id, "force") + except Exception: + pending_rescues.discard(key) + rescue_jobs.pop(job_id, None) + delete_job("rescue_job", job_id) + record["status"] = previous_status + record["job_id"] = previous_job_id + save_rescue_state(profile, canonical_id, record) + raise + LOG.warning("vm rescue force-start queued: job=%s uuid=%s user=%s", + job_id, canonical_id, _session.username) + return {"job_id": job_id, "status": "queued"} + + @app.post("/api/v1/vms/{vm_id}/rescue/exit", status_code=202) + def exit_vm_rescue(vm_id: str, body: ExitRescueBody, + _session: Session = Depends(require_approved_write)): + with reinstall_lock, rescue_lock: + forbid_long_job_during_update() + profile = current_profile() + canonical_id = require_vm_access(_session, profile, vm_id) + vm_scope = host_scope(profile) + key = (vm_scope, canonical_id) + if key in pending_rescues or (template_scope(profile), canonical_id) in pending_reinstalls: + raise VMError("该虚拟机已有救援或重装任务,请等待完成", 409) + record = load_rescue_state(profile, canonical_id) + if record is None: + raise VMError("找不到原始启动配置,无法安全退出救援模式", 409) + vm = new_service(profile).get_vm(canonical_id) + if body.confirmation_name != vm["name"]: + raise VMError("确认名称与虚拟机名称不一致", 422) + if not (vm.get("rescue_mode") or vm.get("rescue_staged")): + raise VMError("虚拟机当前并非救援模式,请管理员核对配置", 409) + job_id = str(uuid.uuid4()) + rescue_jobs[job_id] = { + "scope": vm_scope, "owner": _session.username, + "vm_id": canonical_id, "operation": "exit", + "status": "queued", "phase": "等待退出救援模式", + } + save_job("rescue_job", job_id, rescue_jobs[job_id]) + record["status"] = "exiting" + record["job_id"] = job_id + save_rescue_state(profile, canonical_id, record) + pending_rescues.add(key) + try: + rescue_executor.submit(run_rescue_job, job_id, profile, canonical_id, "exit") + except RuntimeError as exc: + pending_rescues.discard(key) + record["status"] = "active" + save_rescue_state(profile, canonical_id, record) + rescue_jobs.pop(job_id, None) + delete_job("rescue_job", job_id) + raise VMError("面板正在停止,无法退出救援模式", 503) from exc + LOG.info("vm rescue exit queued: job=%s uuid=%s user=%s", + job_id, canonical_id, _session.username) + return {"job_id": job_id, "status": "queued"} + + @app.get("/api/v1/rescue-jobs/{job_id}") + def get_rescue_job(job_id: str, _session: Session = Depends(require_approved)): + profile = current_profile() + vm_scope = host_scope(profile) + with rescue_lock: + job = rescue_jobs.get(job_id) + if (job is None or job["scope"] != vm_scope + or (job["owner"] != _session.username + and not account_for_session(_session)["admin"])): + raise VMError("救援任务不存在", 404) + require_vm_access(_session, profile, job["vm_id"]) + return {key: value for key, value in job.items() + if key not in {"scope", "owner", "vm_id"}} + + @app.post("/api/v1/vms/{vm_id}/actions") + def action(vm_id: str, body: ActionBody, _session: Session = Depends(require_approved_write)): + with reinstall_lock, rescue_lock: + forbid_long_job_during_update() + profile = current_profile() + require_vm_access(_session, profile, vm_id) + try: + normalized_id = str(uuid.UUID(vm_id)) + except ValueError: + normalized_id = vm_id + if (template_scope(profile), normalized_id) in pending_reinstalls: + raise VMError("虚拟机正在重装系统,暂时不能执行其他操作", 409) + service = new_service(profile) + if (host_scope(profile), normalized_id) in pending_rescues: + raise VMError("虚拟机正在切换救援模式,请等待任务完成", 409) + rescue_record = current_rescue_state(profile, normalized_id, service) + current_vm = service.get_vm(normalized_id) + staged = bool(current_vm.get("rescue_staged")) + if staged and rescue_record is not None: + if body.action not in {"poweroff", "start"}: + raise VMError( + "救援 ISO 已预挂载;请强制断电后开机进入救援,或取消救援配置", 409) + elif rescue_record is not None or current_vm.get("rescue_mode") or staged: + raise VMError("虚拟机处于救援模式或救援任务中,请先退出救援模式", 409) + vm = service.action(vm_id, body.action) + if staged and body.action == "start": + if not vm.get("rescue_mode") or vm.get("rescue_staged"): + raise VMError( + "虚拟机已发送开机指令,但未确认从救援 ISO 启动;请检查 VNC 控制台", 502) + rescue_record["status"] = "active" + save_rescue_state(profile, normalized_id, rescue_record) + LOG.info("vm action: uuid=%s action=%s admin=%s", vm.get("uuid"), body.action, _session.username) + return vm + + @app.delete("/api/v1/vms/{vm_id}") + def delete_vm( + vm_id: str, + delete_disks: bool = False, + _session: Session = Depends(require_approved_write), + ): + with reinstall_lock, rescue_lock: + forbid_long_job_during_update() + profile = current_profile() + require_vm_access(_session, profile, vm_id) + try: + normalized_id = str(uuid.UUID(vm_id)) + except ValueError: + normalized_id = vm_id + if (template_scope(profile), normalized_id) in pending_reinstalls: + raise VMError("虚拟机正在重装系统,暂时不能删除", 409) + service = new_service(profile) + rescue_record = current_rescue_state(profile, normalized_id, service) + rescue_vm = service.get_vm(normalized_id) + if ((host_scope(profile), normalized_id) in pending_rescues + or rescue_record is not None + or rescue_vm.get("rescue_mode") + or rescue_vm.get("rescue_staged")): + raise VMError("虚拟机处于救援模式或救援任务中,请先退出救援模式", 409) + result = service.delete_vm(vm_id, delete_disks) + if database_mode: + try: + state.users.delete_vm_owner(host_scope(profile), result["uuid"]) + except DatabaseError: + LOG.exception("Could not remove owner for deleted VM %s", result["uuid"]) + result = {**result, "warning": "虚拟机已删除,但数据库中的归属记录未能清理"} + try: + delete_credential(profile, result["uuid"]) + except DatabaseError: + LOG.exception("Could not remove credential for deleted VM %s", result["uuid"]) + result = {**result, "warning": "虚拟机已删除,但数据库中的登录凭据或归属记录未能完全清理;请检查数据库状态"} + try: + release_vm_public_ip_claims(profile, result["uuid"]) + except DatabaseError: + LOG.exception("Could not release public IP claim for deleted VM %s", result["uuid"]) + result = {**result, "warning": "虚拟机已删除,但公网 IP 占用记录未能清理;请检查数据库状态"} + LOG.info( + "vm deleted: uuid=%s delete_disks=%s admin=%s", + result.get("uuid"), delete_disks, _session.username, + ) + return result + + @app.websocket("/api/v1/vms/{vm_id}/console") + async def console(websocket: WebSocket, vm_id: str): + host = websocket.headers.get("host") + if websocket.url.scheme != "wss": + await websocket.close(code=4403) + return + if not _origin_matches_host(websocket.headers.get("origin"), host): + await websocket.close(code=4403) + return + session = await asyncio.to_thread(sessions.get, websocket.cookies.get(COOKIE_NAME)) + if session is None: + await websocket.close(code=4401) + return + try: + account = await asyncio.to_thread(account_for_session, session) + except HTTPException: + await websocket.close(code=4401) + return + if not account["admin"] and not account["approved"]: + await websocket.close(code=4403) + return + profile = manager.current() + if profile is None: + await websocket.close(code=4409) + return + try: + if profile.get("key_locked"): + await websocket.close(code=4423) + return + await asyncio.to_thread(require_vm_access, session, profile, vm_id) + port = await asyncio.to_thread(new_service(profile).console_port, vm_id) + except VMError: + await websocket.close(code=4404) + return + await websocket.accept() + async def watch_console_access() -> None: + while True: + await asyncio.sleep(CONSOLE_ACCESS_CHECK_SECONDS) + try: + refreshed = await asyncio.to_thread(sessions.get, session.token) + if refreshed is None or refreshed.username != session.username: + return + account = await asyncio.to_thread(account_for_session, refreshed) + if not account["admin"] and not account["approved"]: + return + current = manager.current() + if (current is None or current.get("key_locked") + or host_scope(current) != host_scope(profile)): + return + await asyncio.to_thread(require_vm_access, refreshed, current, vm_id) + except (HTTPException, VMError, DatabaseError, RemoteHostError, + KeyError, TypeError, ValueError): + return + + relay_task = asyncio.create_task(relay_console( + websocket, + port=port, + ssh_target=profile["ssh_target"], + ssh_binary=settings.ssh_binary, + known_hosts_file=profile["ssh_known_hosts_file"], + ssh_config_file=profile["ssh_config_file"], + )) + access_task = asyncio.create_task(watch_console_access()) + try: + done, _pending = await asyncio.wait( + {relay_task, access_task}, return_when=asyncio.FIRST_COMPLETED) + if access_task in done: + relay_task.cancel() + await asyncio.gather(relay_task, return_exceptions=True) + with suppress(RuntimeError, OSError): + await websocket.close(code=4403) + return + await relay_task + except ConsoleRelayError as exc: + LOG.warning("VNC relay failed for vm %r: %s", vm_id, exc) + with suppress(RuntimeError, OSError): + await websocket.close(code=1011) + finally: + access_task.cancel() + await asyncio.gather(access_task, return_exceptions=True) + + return app diff --git a/engine/virsh_panel/auth.py b/engine/virsh_panel/auth.py new file mode 100644 index 00000000..9ba1fb55 --- /dev/null +++ b/engine/virsh_panel/auth.py @@ -0,0 +1,188 @@ +"""Password verification and short-lived, server-side account sessions.""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import secrets +import threading +import time +from dataclasses import dataclass +from typing import Protocol + + +PASSWORD_ITERATIONS = 600_000 +SESSION_LIFETIME_SECONDS = 8 * 60 * 60 + + +def hash_password(password: str) -> str: + if len(password) < 12: + raise ValueError("Password must contain at least 12 characters") + salt = secrets.token_bytes(16) + digest = hashlib.pbkdf2_hmac( + "sha256", password.encode("utf-8"), salt, PASSWORD_ITERATIONS + ) + return f"pbkdf2_sha256${PASSWORD_ITERATIONS}${salt.hex()}${digest.hex()}" + + +def verify_password(password: str, encoded: str) -> bool: + try: + algorithm, iterations_raw, salt_raw, expected_raw = encoded.split("$") + iterations = int(iterations_raw) + if algorithm != "pbkdf2_sha256" or not 100_000 <= iterations <= 2_000_000: + return False + salt = bytes.fromhex(salt_raw) + expected = bytes.fromhex(expected_raw) + if len(salt) < 16 or len(expected) != 32: + return False + except (ValueError, TypeError): + return False + actual = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) + return hmac.compare_digest(actual, expected) + + +@dataclass(frozen=True) +class Session: + token: str + username: str + csrf_token: str + expires_at: float + # Immutable database primary key. The optional form is only for the + # injected, database-free HTTP test harness. + user_id: int | None = None + + +class SessionStore: + def __init__(self) -> None: + self._sessions: dict[str, Session] = {} + self._lock = threading.Lock() + + def issue(self, username: str, user_id: int | None = None) -> Session: + session = Session( + token=secrets.token_urlsafe(32), + username=username, + csrf_token=secrets.token_urlsafe(32), + expires_at=time.time() + SESSION_LIFETIME_SECONDS, + user_id=user_id, + ) + with self._lock: + self._sessions[session.token] = session + return session + + def get(self, token: str | None) -> Session | None: + if not token: + return None + with self._lock: + session = self._sessions.get(token) + if session is None: + return None + if session.expires_at <= time.time(): + self._sessions.pop(token, None) + return None + return session + + def revoke(self, token: str | None) -> None: + if token: + with self._lock: + self._sessions.pop(token, None) + + +class _SessionDatabase(Protocol): + def get(self, record_type: str, record_key: str) -> str | None: ... + def set(self, record_type: str, record_key: str, value: str) -> None: ... + def delete(self, record_type: str, record_key: str) -> None: ... + + +class DatabaseSessionStore: + """Server-side sessions that survive a web-process restart. + + Only a SHA-256 fingerprint of the bearer token is used as the database + record key. The immutable user ID, username, CSRF token and expiry are + encrypted by the database store; the raw bearer token is never persisted. + """ + + def __init__(self, database: _SessionDatabase) -> None: + self._database = database + + @staticmethod + def _key(token: str) -> str: + return hashlib.sha256(token.encode("ascii")).hexdigest() + + def issue(self, username: str, user_id: int | None = None) -> Session: + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Database sessions require a positive user ID") + session = Session( + token=secrets.token_urlsafe(32), + username=username, + csrf_token=secrets.token_urlsafe(32), + expires_at=time.time() + SESSION_LIFETIME_SECONDS, + user_id=user_id, + ) + payload = json.dumps({ + "username": session.username, + "user_id": session.user_id, + "csrf_token": session.csrf_token, + "expires_at": session.expires_at, + }, separators=(",", ":")) + self._database.set("session", self._key(session.token), payload) + return session + + def get(self, token: str | None) -> Session | None: + if not isinstance(token, str) or not token or len(token) > 256: + return None + try: + key = self._key(token) + except UnicodeEncodeError: + return None + raw = self._database.get("session", key) + if raw is None: + return None + try: + data = json.loads(raw) + username = data["username"] + user_id = data["user_id"] + csrf_token = data["csrf_token"] + expires_at = data["expires_at"] + except (TypeError, ValueError, KeyError): + return None + if (not isinstance(username, str) or not isinstance(csrf_token, str) + or isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1 + or isinstance(expires_at, bool) or not isinstance(expires_at, (int, float))): + return None + if expires_at <= time.time(): + self._database.delete("session", key) + return None + return Session(token, username, csrf_token, float(expires_at), user_id) + + def revoke(self, token: str | None) -> None: + if not isinstance(token, str) or not token or len(token) > 256: + return + try: + key = self._key(token) + except UnicodeEncodeError: + return + self._database.delete("session", key) + + +class LoginLimiter: + """Small in-memory limit for failed logins from one peer address.""" + + def __init__(self) -> None: + self._failures: dict[str, list[float]] = {} + self._lock = threading.Lock() + + def allowed(self, peer: str) -> bool: + cutoff = time.time() - 15 * 60 + with self._lock: + recent = [attempt for attempt in self._failures.get(peer, []) if attempt > cutoff] + self._failures[peer] = recent + return len(recent) < 5 + + def failed(self, peer: str) -> None: + with self._lock: + self._failures.setdefault(peer, []).append(time.time()) + + def succeeded(self, peer: str) -> None: + with self._lock: + self._failures.pop(peer, None) diff --git a/engine/virsh_panel/cloud_init.py b/engine/virsh_panel/cloud_init.py new file mode 100644 index 00000000..3d10eb76 --- /dev/null +++ b/engine/virsh_panel/cloud_init.py @@ -0,0 +1,362 @@ +"""Validate public IPv4 guest settings and build a NoCloud seed ISO. + +The seed may contain a guest SSH public key and a salted root password hash, +but never a plaintext password, private key, or panel credential. JSON is +used as a YAML subset so untrusted fields cannot inject directives. +""" + +from __future__ import annotations + +import base64 +import binascii +import ipaddress +import json +import re +import secrets +import string +import uuid +from io import BytesIO +from typing import Any + + +_VM_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z") +_MAC = re.compile(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\Z") +_SSH_TYPES = { + "ssh-ed25519", + "ssh-rsa", + "ecdsa-sha2-nistp256", + "ecdsa-sha2-nistp384", + "ecdsa-sha2-nistp521", +} +_SHA512_CRYPT = re.compile( + r"\$6\$rounds=([1-9][0-9]{3,8})\$[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}\Z" +) + + +def hash_root_password(password: str) -> str: + """Hash a guest root password for /etc/shadow before writing the seed.""" + if (not isinstance(password, str) or not 12 <= len(password) <= 128 + or any(not char.isprintable() for char in password)): + raise ValueError("初始 root 密码须为 12 至 128 个可打印字符") + if (not any(char in string.ascii_uppercase for char in password) + or not any(char in string.ascii_lowercase for char in password) + or not any(not char.isalnum() and not char.isspace() + for char in password)): + raise ValueError("初始 root 密码须包含大写字母、小写字母和符号") + from passlib.hash import sha512_crypt + + return sha512_crypt.using(rounds=100_000).hash(password) + + +def generate_root_password() -> str: + """Generate a high-entropy password satisfying the same guest policy.""" + symbols = "!@#$%*-_=+?" + alphabet = string.ascii_letters + string.digits + symbols + password = [ + secrets.choice(string.ascii_uppercase), + secrets.choice(string.ascii_lowercase), + secrets.choice(symbols), + ] + password.extend(secrets.choice(alphabet) for _ in range(29)) + secrets.SystemRandom().shuffle(password) + return "".join(password) + + +def _validate_guest_auth(guest_ssh_public_key: Any, + root_password_hash: Any) -> tuple[str, str | None]: + if not isinstance(guest_ssh_public_key, str): + raise ValueError("虚拟机 SSH 公钥格式无效") + public_key = guest_ssh_public_key.strip() + if not public_key and not root_password_hash: + raise ValueError("请填写虚拟机 SSH 公钥或初始 root 密码") + if public_key: + public_key = _validate_ssh_public_key(public_key) + if root_password_hash is not None: + if not isinstance(root_password_hash, str): + raise ValueError("初始 root 密码哈希格式无效") + match = _SHA512_CRYPT.fullmatch(root_password_hash) + if match is None or not 100_000 <= int(match.group(1)) <= 1_000_000: + raise ValueError("初始 root 密码哈希格式无效") + return public_key, root_password_hash + + +def _ssh_string(blob: bytes, offset: int) -> tuple[bytes, int]: + if offset + 4 > len(blob): + raise ValueError("SSH 公钥内容无效") + size = int.from_bytes(blob[offset:offset + 4], "big") + start = offset + 4 + end = start + size + if size > 8192 or end > len(blob): + raise ValueError("SSH 公钥内容无效") + return blob[start:end], end + + +def _validate_ssh_public_key(value: Any) -> str: + if not isinstance(value, str) or not value or len(value) > 16384: + raise ValueError("请填写虚拟机登录用的 SSH 公钥") + if any(char in value for char in ("\n", "\r", "\x00")): + raise ValueError("SSH 公钥必须是单行 OpenSSH 公钥") + fields = value.strip().split(maxsplit=2) + if len(fields) < 2 or fields[0] not in _SSH_TYPES: + raise ValueError("SSH 公钥格式无效,仅支持 Ed25519、RSA 或 ECDSA") + key_type, encoded = fields[:2] + try: + blob = base64.b64decode(encoded, validate=True) + embedded_type, offset = _ssh_string(blob, 0) + except (ValueError, binascii.Error) as exc: + raise ValueError("SSH 公钥内容无效") from exc + if embedded_type != key_type.encode("ascii"): + raise ValueError("SSH 公钥类型与内容不匹配") + + # An OpenSSH key is a series of length-prefixed binary strings. Verify + # its structure rather than accepting arbitrary base64 after the prefix. + if key_type == "ssh-ed25519": + key, offset = _ssh_string(blob, offset) + if len(key) != 32: + raise ValueError("Ed25519 公钥长度无效") + elif key_type == "ssh-rsa": + exponent, offset = _ssh_string(blob, offset) + modulus, offset = _ssh_string(blob, offset) + if (not exponent or int.from_bytes(exponent, "big") < 3 + or int.from_bytes(exponent, "big") % 2 == 0 + or int.from_bytes(modulus, "big").bit_length() < 2048): + raise ValueError("RSA 公钥无效或不足 2048 位") + else: + curve, offset = _ssh_string(blob, offset) + point, offset = _ssh_string(blob, offset) + suffix = key_type.removeprefix("ecdsa-sha2-") + point_lengths = {"nistp256": 65, "nistp384": 97, "nistp521": 133} + if (curve != suffix.encode("ascii") or len(point) != point_lengths[suffix] + or point[0] != 4): + raise ValueError("ECDSA 公钥内容无效") + if offset != len(blob): + raise ValueError("SSH 公钥存在多余数据") + # Keep a harmless OpenSSH comment for operator identification. The + # generated user-data is JSON-escaped, not assembled as raw YAML. + return value.strip() + + +def _ipv4(value: Any, label: str) -> ipaddress.IPv4Address: + if not isinstance(value, str) or not value or value != value.strip(): + raise ValueError(f"{label}必须是 IPv4 地址") + try: + address = ipaddress.ip_address(value) + except ValueError as exc: + raise ValueError(f"{label}必须是 IPv4 地址") from exc + if not isinstance(address, ipaddress.IPv4Address): + raise ValueError(f"{label}必须是 IPv4 地址") + return address + + +def validate_cloud_network( + public_ip_cidr: str, + gateway: str, + dns_servers: list[str] | tuple[str, ...], + guest_ssh_public_key: str = "", + root_password_hash: str | None = None, +) -> dict[str, Any]: + """Return canonical guest network fields or raise ``ValueError``. + + This first version supports an on-link gateway on a public IPv4 subnet, + including /24 and /28. Routed /32/off-link gateways need a separate + explicit model; silently treating them as on-link would strand the guest. + """ + if (not isinstance(public_ip_cidr, str) or not public_ip_cidr + or public_ip_cidr != public_ip_cidr.strip()): + raise ValueError("公网 IP 必须采用 IPv4 地址/前缀长度格式,例如实际分配的地址加 /28") + try: + interface = ipaddress.ip_interface(public_ip_cidr) + except ValueError as exc: + raise ValueError("公网 IP/CIDR 格式无效") from exc + if not isinstance(interface, ipaddress.IPv4Interface): + raise ValueError("暂时只支持公网 IPv4") + network = interface.network + if not 1 <= network.prefixlen <= 30: + raise ValueError("当前网桥方案仅支持 /1 到 /30 的 IPv4 前缀") + if (not interface.ip.is_global or interface.ip.is_multicast + or interface.ip.is_reserved): + raise ValueError("IP 不是可用的公网 IPv4 地址") + if interface.ip in (network.network_address, network.broadcast_address): + raise ValueError("不能使用子网地址或广播地址作为虚拟机 IP") + + gateway_ip = _ipv4(gateway, "网关") + if (not gateway_ip.is_global or gateway_ip.is_multicast or gateway_ip.is_reserved + or gateway_ip not in network or gateway_ip == interface.ip + or gateway_ip in (network.network_address, network.broadcast_address)): + raise ValueError("网关必须是同一网段内另一可用 IPv4 地址") + + if (not isinstance(dns_servers, (list, tuple)) or not 1 <= len(dns_servers) <= 4): + raise ValueError("请填写 1 到 4 个 DNS IPv4 地址") + dns_ips = [_ipv4(item, "DNS") for item in dns_servers] + if any(not address.is_global or address.is_multicast or address.is_reserved + for address in dns_ips): + raise ValueError("当前公网模板只支持可公开路由的 DNS IPv4 地址") + dns = [str(address) for address in dns_ips] + if len(set(dns)) != len(dns): + raise ValueError("DNS 地址不能重复") + public_key, password_hash = _validate_guest_auth( + guest_ssh_public_key, root_password_hash) + result = { + "public_ip_cidr": str(interface), + "gateway": str(gateway_ip), + "dns_servers": dns, + "guest_ssh_public_key": public_key, + } + if password_hash is not None: + result["root_password_hash"] = password_hash + return result + + +def build_seed_iso( + vm_uuid: str, + name: str, + mac: str, + validated_network: dict[str, Any], +) -> bytes: + """Build a CIDATA ISO with user-data, meta-data, and network-config.""" + try: + instance_id = str(uuid.UUID(vm_uuid)) + except (ValueError, TypeError, AttributeError) as exc: + raise ValueError("虚拟机 UUID 无效") from exc + if not isinstance(name, str) or not _VM_NAME.fullmatch(name): + raise ValueError("虚拟机名称无效") + if not isinstance(mac, str) or not _MAC.fullmatch(mac): + raise ValueError("虚拟机 MAC 地址无效") + normalized_mac = mac.lower() + mac_octets = [int(part, 16) for part in normalized_mac.split(":")] + if mac_octets[0] & 1 or not any(mac_octets): + raise ValueError("虚拟机 MAC 地址不能是组播或全零地址") + if not isinstance(validated_network, dict): + raise ValueError("网络配置无效") + network = validate_cloud_network( + validated_network.get("public_ip_cidr"), + validated_network.get("gateway"), + validated_network.get("dns_servers"), + validated_network.get("guest_ssh_public_key"), + validated_network.get("root_password_hash"), + ) + + # Keep Linux hostname valid even when the libvirt VM name contains dots or + # underscores. The libvirt name itself remains unchanged. + hostname = re.sub(r"[^a-z0-9-]", "-", name.lower()).strip("-")[:63] + if not hostname: + hostname = f"vm-{instance_id[:8]}" + use_public_key = bool(network["guest_ssh_public_key"]) + use_password = bool(network.get("root_password_hash")) + root_user: dict[str, Any] = {"name": "root", "lock_passwd": not use_password} + if use_public_key: + root_user["ssh_authorized_keys"] = [network["guest_ssh_public_key"]] + if use_password: + root_user["hashed_passwd"] = network["root_password_hash"] + # RHEL/AlmaLinux 10 defaults to prohibit-password for root. An early + # drop-in makes the two requested authentication modes explicit; cloud-init + # itself writes a later 50-cloud-init.conf for PasswordAuthentication. + sshd_config = ( + ("PermitRootLogin yes\nPasswordAuthentication yes\n" if use_password else + "PermitRootLogin prohibit-password\nPasswordAuthentication no\n") + + "KbdInteractiveAuthentication no\n" + ) + user_data = { + "users": [root_user], + "ssh_pwauth": use_password, + "disable_root": False, + "write_files": [{ + "path": "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf", + "content": sshd_config, + "permissions": "0644", + }], + } + metadata = {"instance-id": instance_id, "local-hostname": hostname} + network_config = { + "version": 2, + "ethernets": { + "public0": { + "match": {"macaddress": normalized_mac}, + "dhcp4": False, + "dhcp6": False, + "addresses": [network["public_ip_cidr"]], + "routes": [{"to": "0.0.0.0/0", "via": network["gateway"]}], + "nameservers": {"addresses": network["dns_servers"]}, + }, + }, + } + + files = ( + ("/USERDATA.;1", "user-data", "/user-data", + b"#cloud-config\n" + json.dumps(user_data, ensure_ascii=True).encode("ascii") + b"\n"), + ("/METADATA.;1", "meta-data", "/meta-data", + json.dumps(metadata, ensure_ascii=True).encode("ascii") + b"\n"), + ("/NETWORK.;1", "network-config", "/network-config", + json.dumps(network_config, ensure_ascii=True).encode("ascii") + b"\n"), + ) + import pycdlib + + iso = pycdlib.PyCdlib() + payloads: list[BytesIO] = [] + try: + iso.new(vol_ident="CIDATA", rock_ridge="1.09", joliet=3) + for iso_path, rock_ridge_name, joliet_path, contents in files: + payload = BytesIO(contents) + payloads.append(payload) # pycdlib reads these during write_fp. + iso.add_fp(payload, len(contents), iso_path=iso_path, + rr_name=rock_ridge_name, joliet_path=joliet_path) + output = BytesIO() + iso.write_fp(output) + return output.getvalue() + finally: + iso.close() + + +def read_seed_network(seed: bytes) -> dict[str, Any]: + """Read the network settings from a panel-created NoCloud ISO. + + Only the network-config file is parsed: user-data can contain a password + hash or an SSH key and must never be returned to the web API. + """ + if not isinstance(seed, bytes) or not seed or len(seed) > 1024 * 1024: + raise ValueError("原 cloud-init 配置盘大小无效") + import pycdlib + + iso = pycdlib.PyCdlib() + opened = False + try: + iso.open_fp(BytesIO(seed)) + opened = True + output = BytesIO() + iso.get_file_from_iso_fp(output, rr_path="/network-config") + raw = output.getvalue() + if len(raw) > 65536: + raise ValueError("原网络配置过大") + config = json.loads(raw) + except (OSError, KeyError, TypeError, ValueError, pycdlib.pycdlibexception.PyCdlibException) as exc: + raise ValueError("无法读取原 cloud-init 网络配置") from exc + finally: + if opened: + iso.close() + + try: + if config["version"] != 2: + raise ValueError + ethernets = config["ethernets"] + if not isinstance(ethernets, dict) or set(ethernets) != {"public0"}: + raise ValueError + public = ethernets["public0"] + if public["dhcp4"] is not False or public["dhcp6"] is not False: + raise ValueError + addresses = public["addresses"] + routes = public["routes"] + dns = public["nameservers"]["addresses"] + mac = public["match"]["macaddress"] + if (not isinstance(addresses, list) or len(addresses) != 1 + or not isinstance(routes, list) or len(routes) != 1 + or routes[0]["to"] != "0.0.0.0/0" + or not isinstance(mac, str) or not _MAC.fullmatch(mac)): + raise ValueError + return { + "public_ip_cidr": addresses[0], + "gateway": routes[0]["via"], + "dns_servers": dns, + "mac": mac.lower(), + } + except (KeyError, TypeError, ValueError) as exc: + raise ValueError("原 cloud-init 网络配置格式无效") from exc diff --git a/engine/virsh_panel/cloud_templates.py b/engine/virsh_panel/cloud_templates.py new file mode 100644 index 00000000..89ba0fb4 --- /dev/null +++ b/engine/virsh_panel/cloud_templates.py @@ -0,0 +1,273 @@ +"""Private cloud-image catalog and verified AlmaLinux image downloads.""" + +from __future__ import annotations + +import fcntl +import hashlib +import json +import os +import re +import stat +import struct +import tempfile +import threading +import time +import urllib.error +import urllib.request +from contextlib import contextmanager +from pathlib import Path +from urllib.parse import urlsplit + + +MAX_IMAGE_BYTES = 4 * 1024**3 +MAX_VIRTUAL_BYTES = 4096 * 1024**3 +MAX_DOWNLOAD_SECONDS = 3600 +GIB = 1024**3 +IMAGE_PATH = re.compile( + r"/almalinux/(?P9|10)/cloud/x86_64/images/" + r"AlmaLinux-(?P=version)-GenericCloud-[A-Za-z0-9._-]+\.x86_64\.qcow2\Z" +) +SHA256_RE = re.compile(r"[0-9a-fA-F]{64}\Z") + + +class TemplateError(Exception): + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +class _RejectRedirects(urllib.request.HTTPRedirectHandler): + """Never let a validated official URL redirect to a different target.""" + + def redirect_request(self, request, file_pointer, code, message, headers, new_url): + raise TemplateError("官方镜像地址发生重定向,请使用最终的官方 HTTPS 直链", 422) + + +def template_scope(profile: dict) -> str: + """Bind template records to this SSH host identity and disk pool.""" + if profile.get("host_id"): + raw = json.dumps(["virt-cloud", profile["host_id"], profile["storage_pool"]]) + return hashlib.sha256(raw.encode("ascii")).hexdigest() + keys = ("host", "port", "fingerprint", "storage_pool") + if not all(key in profile for key in keys): + raise TemplateError("宿主机资料不完整,无法选择镜像模板", 409) + identity = json.dumps([profile[key] for key in keys], ensure_ascii=False, + separators=(",", ":")) + return hashlib.sha256(identity.encode("utf-8")).hexdigest() + + +def validate_image_url(url: str) -> str: + if not isinstance(url, str) or len(url) > 2048: + raise TemplateError("云镜像地址无效") + try: + parsed = urlsplit(url) + except ValueError as exc: + raise TemplateError("云镜像地址无效") from exc + try: + port = parsed.port + except ValueError as exc: + raise TemplateError("云镜像地址无效") from exc + if (parsed.scheme != "https" or parsed.hostname != "repo.almalinux.org" + or port not in (None, 443) or parsed.username or parsed.password + or parsed.query or parsed.fragment or not IMAGE_PATH.fullmatch(parsed.path)): + raise TemplateError("仅支持 AlmaLinux 官方仓库的 9/10 x86_64 GenericCloud qcow2 镜像") + return url + + +def image_version_for(url: str) -> str: + """Derive the OS major version from an already restricted official URL.""" + validate_image_url(url) + match = IMAGE_PATH.fullmatch(urlsplit(url).path) + assert match is not None + return match.group("version") + + +def validate_template_name(name: str) -> str: + if not isinstance(name, str) or not 1 <= len(name.strip()) <= 64: + raise TemplateError("模板名称应为 1 至 64 个字符") + if any(ord(char) < 32 or ord(char) == 127 for char in name): + raise TemplateError("模板名称不能包含控制字符") + return name.strip() + + +def template_id_for(scope: str, digest: str, version: str = "10") -> str: + if version not in ("9", "10"): + raise TemplateError("云镜像系统版本无效") + return f"alma{version}-{scope[:8]}-{digest[:16]}" + + +def template_volume_name(template_id: str) -> str: + if not re.fullmatch(r"alma(?:9|10)-[0-9a-f]{8}-[0-9a-f]{16}", template_id): + raise TemplateError("模板标识无效") + return f"panel-template-{template_id}.qcow2" + + +def download_verified_image(url: str, expected_sha256: str, directory: Path) -> tuple[Path, int]: + """Download to a private temporary file; return path and qcow2 virtual size.""" + validate_image_url(url) + if not isinstance(expected_sha256, str) or not SHA256_RE.fullmatch(expected_sha256): + raise TemplateError("请填写 64 位 SHA-256 校验值") + request = urllib.request.Request(url, headers={"User-Agent": "virsh-panel/1"}) + fd, raw_path = tempfile.mkstemp(prefix=".cloud-image-", suffix=".qcow2", dir=directory) + image_path = Path(raw_path) + try: + os.fchmod(fd, 0o600) + checksum = hashlib.sha256() + size = 0 + deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS + try: + opener = urllib.request.build_opener(_RejectRedirects()) + with opener.open(request, timeout=30) as response, os.fdopen(fd, "wb") as output: + fd = -1 + while True: + if time.monotonic() > deadline: + raise TemplateError("云镜像下载超过 60 分钟,请检查面板服务器网络", 504) + chunk = response.read(1024 * 1024) + if not chunk: + break + size += len(chunk) + if size > MAX_IMAGE_BYTES: + raise TemplateError("云镜像超过 4 GiB 限制", 413) + output.write(chunk) + checksum.update(chunk) + output.flush() + os.fsync(output.fileno()) + except (OSError, urllib.error.URLError) as exc: + raise TemplateError("下载官方云镜像失败,请检查面板服务器网络", 502) from exc + if checksum.hexdigest() != expected_sha256.lower(): + raise TemplateError("云镜像 SHA-256 不匹配,已丢弃下载内容", 422) + with image_path.open("rb") as image: + header = image.read(104) + if len(header) < 72 or header[:4] != b"QFI\xfb": + raise TemplateError("下载文件不是有效的 qcow2 镜像", 422) + version = struct.unpack(">I", header[4:8])[0] + backing_offset = struct.unpack(">Q", header[8:16])[0] + cluster_bits = struct.unpack(">I", header[20:24])[0] + virtual_size = struct.unpack(">Q", header[24:32])[0] + crypt_method = struct.unpack(">I", header[32:36])[0] + if version not in (2, 3) or not 9 <= cluster_bits <= 21: + raise TemplateError("云镜像 qcow2 版本或簇大小不受支持", 422) + if version == 3: + if len(header) < 104: + raise TemplateError("云镜像 qcow2 头部不完整", 422) + incompatible = struct.unpack(">Q", header[72:80])[0] + header_length = struct.unpack(">I", header[100:104])[0] + # The external data-file, dirty and corrupt flags all make this + # unsuitable as a standalone template. Reject unknown features. + if (incompatible & ~0x18 or header_length < 104 + or header_length > 1 << cluster_bits or header_length % 8): + raise TemplateError("云镜像包含不受支持或外部依赖的 qcow2 特性", 422) + if backing_offset or crypt_method or not GIB <= virtual_size <= MAX_VIRTUAL_BYTES: + raise TemplateError("云镜像含外部依赖、加密或容量超出支持范围", 422) + return image_path, virtual_size + except BaseException: + image_path.unlink(missing_ok=True) + raise + finally: + if fd >= 0: + os.close(fd) + + +class TemplateStore: + """Small atomic catalog; never stores guest credentials or SSH keys.""" + + def __init__(self, data_dir: Path) -> None: + self.directory = Path(data_dir) + self.file = self.directory / "templates.json" + self.lock_file = self.directory / ".templates.lock" + self._lock = threading.RLock() + + @contextmanager + def _locked(self): + with self._lock: + flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(self.lock_file, flags, 0o600) + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise TemplateError("模板锁文件权限不安全", 500) + fcntl.flock(fd, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(fd, fcntl.LOCK_UN) + finally: + os.close(fd) + + def _read(self) -> dict: + try: + info = self.file.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise TemplateError("模板目录文件权限不安全", 500) + with self.file.open("r", encoding="utf-8") as stream: + data = json.load(stream) + except FileNotFoundError: + return {"version": 1, "templates": []} + except (OSError, ValueError, json.JSONDecodeError) as exc: + raise TemplateError("模板目录文件损坏或不可读取", 500) from exc + if (not isinstance(data, dict) or data.get("version") != 1 + or not isinstance(data.get("templates"), list)): + raise TemplateError("模板目录文件格式无效", 500) + return data + + def _write(self, data: dict) -> None: + fd, raw_path = tempfile.mkstemp(prefix=".templates-", dir=self.directory) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(data, stream, ensure_ascii=False, separators=(",", ":")) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(raw_path, self.file) + directory_fd = os.open(self.directory, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + finally: + if os.path.exists(raw_path): + os.unlink(raw_path) + + def list(self, scope: str) -> list[dict]: + with self._locked(): + records = self._read()["templates"] + return [{key: value for key, value in record.items() if key != "scope"} + for record in records if record.get("scope") == scope] + + def get(self, scope: str, template_id: str) -> dict: + for record in self.list(scope): + if record.get("id") == template_id: + return record + raise TemplateError("模板不存在或不属于当前宿主机", 404) + + def add(self, scope: str, record: dict) -> dict: + with self._locked(): + data = self._read() + if any(item.get("scope") == scope and item.get("id") == record["id"] + for item in data["templates"]): + raise TemplateError("此云镜像已导入", 409) + if any(item.get("scope") == scope + and item.get("name", "").casefold() == record["name"].casefold() + for item in data["templates"]): + raise TemplateError("当前宿主机已有同名云镜像模板", 409) + data["templates"].append({**record, "scope": scope}) + self._write(data) + return record + + def rename(self, scope: str, template_id: str, name: str) -> dict: + name = validate_template_name(name) + with self._locked(): + data = self._read() + target = next((record for record in data["templates"] + if record.get("scope") == scope and record.get("id") == template_id), + None) + if target is None: + raise TemplateError("模板不存在或不属于当前宿主机", 404) + if any(record.get("scope") == scope and record.get("id") != template_id + and record.get("name", "").casefold() == name.casefold() + for record in data["templates"]): + raise TemplateError("当前宿主机已有同名云镜像模板", 409) + target["name"] = name + self._write(data) + return {key: value for key, value in target.items() if key != "scope"} diff --git a/engine/virsh_panel/config.py b/engine/virsh_panel/config.py new file mode 100644 index 00000000..041662ea --- /dev/null +++ b/engine/virsh_panel/config.py @@ -0,0 +1,43 @@ +"""Minimal runtime settings; administrator and host settings live in the panel UI.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path + + +PROJECT_DIR = Path(__file__).resolve().parent.parent +DEFAULT_DATA_DIR = PROJECT_DIR / "data" + + +@dataclass(frozen=True) +class Settings: + """Settings needed before the first browser-based setup step. + + The application creates ``data_dir`` and a one-time setup token. No + administrator password, SSH key, or hypervisor address is read from an + environment file. + """ + + data_dir: Path = DEFAULT_DATA_DIR + static_dir: Path = PROJECT_DIR / "static" + ssh_binary: str = "ssh" + secure_cookie: bool = True + + def validate(self) -> None: + if not self.data_dir.is_absolute() or self.data_dir == Path("/"): + raise ValueError("PANEL_DATA_DIR must be an absolute, dedicated directory") + if not self.static_dir.is_dir(): + raise ValueError(f"Static directory does not exist: {self.static_dir}") + if not self.ssh_binary or "\x00" in self.ssh_binary: + raise ValueError("PANEL_SSH_BINARY must name an executable") + + @classmethod + def from_env(cls) -> "Settings": + settings = cls( + data_dir=Path(os.environ.get("PANEL_DATA_DIR", str(DEFAULT_DATA_DIR))), + ssh_binary=os.environ.get("PANEL_SSH_BINARY", "ssh"), + ) + settings.validate() + return settings diff --git a/engine/virsh_panel/console.py b/engine/virsh_panel/console.py new file mode 100644 index 00000000..24bf568f --- /dev/null +++ b/engine/virsh_panel/console.py @@ -0,0 +1,195 @@ +"""Relay a browser VNC WebSocket to a host-local VNC socket over SSH. + +The caller authenticates and accepts the WebSocket, then obtains the VNC port +from libvirt. No VNC listener needs to be exposed outside the hypervisor. +""" + +from __future__ import annotations + +import asyncio +import os +import re +from typing import Any, Protocol + +try: + from starlette.websockets import WebSocketDisconnect +except ImportError: # The relay can also be tested without the web framework. + class WebSocketDisconnect(Exception): + pass + + +_SSH_TARGET = re.compile( + r"(?:[A-Za-z_][A-Za-z0-9_.-]*@)?[A-Za-z0-9][A-Za-z0-9.-]*\Z" +) +_CHUNK_SIZE = 64 * 1024 +_EXIT_TIMEOUT = 5.0 + + +class ConsoleRelayError(Exception): + """The SSH transport or VNC WebSocket could not be relayed.""" + + +class ConsoleWebSocket(Protocol): + async def receive(self) -> dict[str, Any]: ... + + async def send_bytes(self, data: bytes) -> None: ... + + +def _validate_connection( + port: int, + ssh_target: str, + ssh_binary: str, + known_hosts_file: str | None, + ssh_config_file: str | None, +) -> None: + if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: + raise ValueError("VNC port must be an integer between 1 and 65535") + if not isinstance(ssh_target, str) or not _SSH_TARGET.fullmatch(ssh_target): + raise ValueError("SSH target must be a hostname or user@hostname") + if not isinstance(ssh_binary, str) or not ssh_binary or "\x00" in ssh_binary: + raise ValueError("SSH binary must be a non-empty executable name") + if known_hosts_file is not None and ( + not isinstance(known_hosts_file, str) + or not os.path.isabs(known_hosts_file) + or any(char in known_hosts_file for char in "\r\n\x00") + ): + raise ValueError("known_hosts_file must be an absolute path") + if ssh_config_file is not None and ( + not isinstance(ssh_config_file, str) + or not os.path.isabs(ssh_config_file) + or any(char in ssh_config_file for char in "\r\n\x00") + ): + raise ValueError("ssh_config_file must be an absolute path") + + +async def relay_console( + websocket: ConsoleWebSocket, + *, + port: int, + ssh_target: str, + ssh_binary: str = "ssh", + known_hosts_file: str | None = None, + ssh_config_file: str | None = None, +) -> None: + """Bridge binary WebSocket frames to SSH's ``-W`` TCP forwarding stream. + + ``websocket`` must already be accepted. The target is deliberately limited + to a host or user@host so an untrusted value cannot become an SSH option or + a command. The VNC destination is always the hypervisor's loopback address. + """ + _validate_connection(port, ssh_target, ssh_binary, known_hosts_file, ssh_config_file) + + command = [ssh_binary] + if ssh_config_file is not None: + command.extend(("-F", ssh_config_file)) + command.extend([ + "-T", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=2", + ]) + if known_hosts_file is not None: + command.extend(("-o", f"UserKnownHostsFile={known_hosts_file}")) + command.extend(("-W", f"127.0.0.1:{port}", ssh_target)) + + try: + process = await asyncio.create_subprocess_exec( + *command, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + except OSError as exc: + raise ConsoleRelayError("Could not start the SSH client") from exc + + assert process.stdin is not None + assert process.stdout is not None + + async def browser_to_host() -> bool: + while True: + message = await websocket.receive() + message_type = message.get("type") + if message_type == "websocket.disconnect": + return False + if message_type != "websocket.receive": + raise ConsoleRelayError("Unexpected WebSocket message") + payload = message.get("bytes") + if not isinstance(payload, bytes): + raise ConsoleRelayError("VNC console requires binary WebSocket frames") + try: + process.stdin.write(payload) + await process.stdin.drain() + except (BrokenPipeError, ConnectionResetError): + return True + + async def host_to_browser() -> bool: + while chunk := await process.stdout.read(_CHUNK_SIZE): + try: + await websocket.send_bytes(chunk) + except (OSError, RuntimeError, WebSocketDisconnect): + # ASGI servers may use either exception when the client closes. + return False + return True + + upload = asyncio.create_task(browser_to_host()) + download = asyncio.create_task(host_to_browser()) + try: + done, _ = await asyncio.wait( + {upload, download}, return_when=asyncio.FIRST_COMPLETED + ) + # Resolve exceptions before interpreting a concurrent disconnect. + for task in done: + task.result() + if any(task.result() is False for task in done): + return + if upload in done and download not in done: + # A broken SSH pipe can precede stdout EOF. Wait for the SSH + # process so an authentication/forwarding failure is reported. + try: + if await asyncio.wait_for(download, _EXIT_TIMEOUT) is False: + return + except asyncio.TimeoutError as exc: + raise ConsoleRelayError("SSH client did not close VNC") from exc + if download.done(): + try: + returncode = await asyncio.wait_for(process.wait(), _EXIT_TIMEOUT) + except asyncio.TimeoutError as exc: + raise ConsoleRelayError("SSH client did not exit after closing VNC") from exc + if returncode != 0: + raise ConsoleRelayError(f"SSH client exited with status {returncode}") + finally: + for task in (upload, download): + if not task.done(): + task.cancel() + await asyncio.gather(upload, download, return_exceptions=True) + process.stdin.close() + if process.returncode is None: + # Continue draining the pipe after the browser disconnects; + # otherwise a full stdout pipe can delay subprocess.wait(). + async def discard_output() -> None: + while await process.stdout.read(_CHUNK_SIZE): + pass + + discard = asyncio.create_task(discard_output()) + try: + try: + process.terminate() + except ProcessLookupError: + pass + try: + await asyncio.wait_for(process.wait(), _EXIT_TIMEOUT) + except asyncio.TimeoutError: + if process.returncode is None: + try: + process.kill() + except ProcessLookupError: + pass + await process.wait() + finally: + discard.cancel() + await asyncio.gather(discard, return_exceptions=True) diff --git a/engine/virsh_panel/database.py b/engine/virsh_panel/database.py new file mode 100644 index 00000000..2d3f90b0 --- /dev/null +++ b/engine/virsh_panel/database.py @@ -0,0 +1,994 @@ +"""MariaDB-backed panel state with authenticated encryption at rest. + +The database is the durable source of truth. OpenSSH still needs ordinary +files while it runs, so the remote-host adapter builds those in a private +tmpfs directory on Linux and removes them when the panel stops. Only a +non-secret executable wrapper is written to the panel's data directory. +""" + +from __future__ import annotations + +import hmac +import json +import logging +import math +import os +import re +import secrets +import shutil +import stat +import sys +import threading +import time +import uuid +from dataclasses import replace +from pathlib import Path +from typing import Any, Mapping +from urllib.parse import quote + +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +try: + import pymysql +except ImportError: # Allows package tooling to import without optional DB extras. + pymysql = None + +from .cloud_templates import TemplateError, validate_template_name +from .panel_state import PanelState, SetupError, _USERNAME +from .remote_host import ( + LIBVIRT_URI, + SSH_ALIAS, + HostProfile, + RemoteHostError, + RemoteHostManager, + StagedHost, + _fingerprint, + _key_parts, + _quoted_path, + _validate_host, + _validate_network_selector, + _validate_pool_selector, + _validate_port, + _validate_private_key, + _validate_region, + _write_private, + validate_public_pool, +) +from .ssh_agent import SSHAgentSession, _ASKPASS_SOURCE + + +_RECORD_NAME = re.compile(r"[A-Za-z0-9_.:-]{1,191}\Z") +_RUNTIME_NAME = re.compile(r"v([0-9]+)-[0-9a-f]{4}\Z") +_ENVELOPE_VERSION = b"vp1" +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS panel_records ( + record_type VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + record_key VARCHAR(191) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + encrypted_value LONGBLOB NOT NULL, + PRIMARY KEY (record_type, record_key) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_METRIC_SCHEMA = """ +CREATE TABLE IF NOT EXISTS vm_metric_samples ( + host_scope CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + vm_uuid CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + sampled_at BIGINT UNSIGNED NOT NULL, + cpu_percent DOUBLE NULL, + memory_used_mib DOUBLE NULL, + memory_total_mib DOUBLE NULL, + disk_read_bps DOUBLE NULL, + disk_write_bps DOUBLE NULL, + network_rx_bps DOUBLE NULL, + network_tx_bps DOUBLE NULL, + PRIMARY KEY (host_scope, vm_uuid, sampled_at), + KEY vm_metric_retention (sampled_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_USERS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS users ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + username VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + email VARCHAR(254) CHARACTER SET ascii COLLATE ascii_bin NULL, + password_hash VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + admin TINYINT(1) NOT NULL DEFAULT 0, + approved TINYINT(1) NOT NULL DEFAULT 0, + email_verified TINYINT(1) NOT NULL DEFAULT 0, + created_at BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY user_username (username), + UNIQUE KEY user_email (email) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_REGISTRATION_CODE_SCHEMA = """ +CREATE TABLE IF NOT EXISTS registration_codes ( + email VARCHAR(254) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + code_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + sent_at BIGINT UNSIGNED NOT NULL, + expires_at BIGINT UNSIGNED NOT NULL, + failed_attempts TINYINT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY (email), + KEY code_expiry (expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_VM_OWNERSHIP_SCHEMA = """ +CREATE TABLE IF NOT EXISTS vm_ownership ( + host_scope CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + vm_uuid CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + created_at BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (host_scope, vm_uuid), + KEY vm_owner_user (user_id, host_scope), + CONSTRAINT vm_owner_user_fk FOREIGN KEY (user_id) REFERENCES users(id) + ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_USER_SSH_KEYS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS user_ssh_keys ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT UNSIGNED NOT NULL, + name VARCHAR(80) NOT NULL, + public_key TEXT CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + fingerprint VARCHAR(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + created_at BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY user_ssh_key_fingerprint (user_id, fingerprint), + KEY user_ssh_key_listing (user_id, created_at), + CONSTRAINT user_ssh_key_user_fk FOREIGN KEY (user_id) REFERENCES users(id) + ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_METRIC_COLUMNS = ( + "cpu_percent", "memory_used_mib", "memory_total_mib", "disk_read_bps", + "disk_write_bps", "network_rx_bps", "network_tx_bps", +) +_HOST_SCOPE = re.compile(r"[0-9a-f]{64}\Z") +_METRIC_PRUNE_BATCH_SIZE = 5000 +LOG = logging.getLogger(__name__) + + +class DatabaseError(Exception): + """A database failure that does not echo connection credentials.""" + + def __init__(self, message: str = "数据库连接或读写失败,请检查数据库配置和服务状态") -> None: + super().__init__(message) + self.status = 503 + + +class DatabaseStore: + """Small encrypted record store backed by a single InnoDB table. + + A unique `(record_type, record_key)` key makes insert-only operations + atomic across panel processes. Each record uses a fresh AES-GCM nonce and + binds the ciphertext to its database key through associated data. + """ + + RECORD_TABLE = "panel_records" + METRIC_TABLE = "vm_metric_samples" + + def __init__(self, config: Mapping[str, Any], master_key: bytes) -> None: + if pymysql is None: + raise DatabaseError("缺少 PyMySQL 依赖,请安装面板 requirements.txt") + if not isinstance(master_key, bytes) or len(master_key) != 32: + raise ValueError("Database master key must be 32 bytes") + if not isinstance(config, Mapping): + raise ValueError("Database configuration is invalid") + try: + host = config["host"] + port = config["port"] + database = config["database"] + username = config["username"] + password = config["password"] + except KeyError as exc: + raise ValueError("Database configuration is incomplete") from exc + if (not isinstance(host, str) or not 1 <= len(host) <= 253 + or any(char in host for char in "\r\n\x00")): + raise ValueError("Database host is invalid") + if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: + raise ValueError("Database port is invalid") + if (not isinstance(database, str) or not re.fullmatch(r"[A-Za-z0-9_]{1,64}", database) + or not isinstance(username, str) or not 1 <= len(username) <= 128 + or any(char in username for char in "\r\n\x00") + or not isinstance(password, str)): + raise ValueError("Database credentials are invalid") + self._config = { + "host": host, + "port": port, + "database": database, + "user": username, + "password": password, + "charset": "utf8mb4", + "cursorclass": pymysql.cursors.DictCursor, + "connect_timeout": 5, + "read_timeout": 10, + "write_timeout": 10, + "autocommit": False, + } + if config.get("ssl_ca"): + self._config["ssl"] = {"ca": config["ssl_ca"], "check_hostname": True} + self._config["ssl_verify_cert"] = True + self._config["ssl_verify_identity"] = True + self._cipher = AESGCM(master_key) + self._initialize_schema() + + @staticmethod + def _validate_key(record_type: str, record_key: str) -> None: + if (not isinstance(record_type, str) or len(record_type) > 32 + or not _RECORD_NAME.fullmatch(record_type) + or not isinstance(record_key, str) or not _RECORD_NAME.fullmatch(record_key)): + raise ValueError("Database record name is invalid") + + def _connect(self): + try: + return pymysql.connect(**self._config) + except pymysql.MySQLError as exc: + raise DatabaseError() from exc + + def _initialize_schema(self) -> None: + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute(_SCHEMA) + cursor.execute(_METRIC_SCHEMA) + cursor.execute(_USERS_SCHEMA) + cursor.execute(_REGISTRATION_CODE_SCHEMA) + cursor.execute(_VM_OWNERSHIP_SCHEMA) + cursor.execute(_USER_SSH_KEYS_SCHEMA) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法初始化数据库表,请检查账号建表权限") from exc + finally: + connection.close() + + @staticmethod + def _metric_identity(host_scope: str, vm_id: str) -> str: + if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope): + raise ValueError("Metric host scope is invalid") + try: + canonical = str(uuid.UUID(vm_id)) + except (TypeError, ValueError, AttributeError) as exc: + raise ValueError("Metric VM UUID is invalid") from exc + return canonical + + def save_metric_samples(self, host_scope: str, points: list[dict[str, Any]]) -> None: + if not points: + return + rows = [] + for point in points: + vm_id = self._metric_identity(host_scope, point["vm_id"]) + timestamp = point["timestamp"] + if isinstance(timestamp, bool) or not isinstance(timestamp, int) or timestamp < 0: + raise ValueError("Metric timestamp is invalid") + metrics = [] + for name in _METRIC_COLUMNS: + value = point.get(name) + if (value is not None and (isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) or value < 0)): + raise ValueError("Metric value is invalid") + metrics.append(value) + rows.append((host_scope, vm_id, timestamp, *metrics)) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.executemany( + f"INSERT INTO {self.METRIC_TABLE} (host_scope, vm_uuid, sampled_at, " + + ", ".join(_METRIC_COLUMNS) + ") VALUES (" + + ", ".join(["%s"] * (3 + len(_METRIC_COLUMNS))) + ") " + "ON DUPLICATE KEY UPDATE " + + ", ".join(f"{name}=VALUES({name})" for name in _METRIC_COLUMNS), + rows, + ) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法保存虚拟机指标") from exc + finally: + connection.close() + + def prune_metric_samples(self, cutoff: int) -> int: + if isinstance(cutoff, bool) or not isinstance(cutoff, int) or cutoff < 0: + raise ValueError("Metric retention cutoff is invalid") + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + f"DELETE FROM {self.METRIC_TABLE} WHERE sampled_at < %s " + "ORDER BY sampled_at LIMIT %s", + (cutoff, _METRIC_PRUNE_BATCH_SIZE), + ) + removed = cursor.rowcount + connection.commit() + return max(0, removed) + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法清理过期虚拟机指标") from exc + finally: + connection.close() + + def query_metric_samples(self, host_scope: str, vm_id: str, *, + since: int, until: int, interval_seconds: int, + limit: int = 600) -> list[dict[str, Any]]: + vm_id = self._metric_identity(host_scope, vm_id) + if (any(isinstance(value, bool) or not isinstance(value, int) + for value in (since, until, interval_seconds, limit)) + or since < 0 or until < since or interval_seconds < 60 + or not 1 <= limit <= 600): + raise ValueError("Metric query range is invalid") + columns = ", ".join(f"AVG({name}) AS {name}" for name in _METRIC_COLUMNS) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT MAX(sampled_at) AS timestamp, " + columns + + f" FROM {self.METRIC_TABLE} " + "WHERE host_scope=%s AND vm_uuid=%s AND sampled_at >= %s " + "AND sampled_at <= %s GROUP BY FLOOR(sampled_at / %s) " + "ORDER BY timestamp ASC LIMIT %s", + (host_scope, vm_id, since, until, interval_seconds, limit), + ) + rows = cursor.fetchall() + return [ + {"timestamp": int(row["timestamp"]), + **{name: float(row[name]) if row[name] is not None else None + for name in _METRIC_COLUMNS}} + for row in rows + ] + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取虚拟机指标") from exc + finally: + connection.close() + + def _encrypt(self, record_type: str, record_key: str, value: str) -> bytes: + if not isinstance(value, str): + raise TypeError("Database value must be a string") + nonce = secrets.token_bytes(12) + associated_data = f"{record_type}\x00{record_key}".encode("ascii") + return _ENVELOPE_VERSION + nonce + self._cipher.encrypt( + nonce, value.encode("utf-8"), associated_data, + ) + + def _decrypt(self, record_type: str, record_key: str, payload: bytes) -> str: + if not isinstance(payload, (bytes, bytearray)) or not payload.startswith(_ENVELOPE_VERSION): + raise DatabaseError("数据库密文格式无效或主密钥不匹配") + nonce = bytes(payload[3:15]) + ciphertext = bytes(payload[15:]) + if len(nonce) != 12 or len(ciphertext) < 16: + raise DatabaseError("数据库密文格式无效或主密钥不匹配") + try: + return self._cipher.decrypt( + nonce, ciphertext, f"{record_type}\x00{record_key}".encode("ascii"), + ).decode("utf-8") + except (ValueError, UnicodeError) as exc: + raise DatabaseError("数据库密文格式无效或主密钥不匹配") from exc + except Exception as exc: + # InvalidTag does not reveal whether the key or ciphertext is wrong. + raise DatabaseError("数据库密文格式无效或主密钥不匹配") from exc + + def get(self, record_type: str, record_key: str) -> str | None: + self._validate_key(record_type, record_key) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + f"SELECT encrypted_value FROM {self.RECORD_TABLE} " + "WHERE record_type=%s AND record_key=%s", + (record_type, record_key), + ) + row = cursor.fetchone() + return None if row is None else self._decrypt( + record_type, record_key, row["encrypted_value"], + ) + except pymysql.MySQLError as exc: + raise DatabaseError() from exc + finally: + connection.close() + + def set(self, record_type: str, record_key: str, value: str) -> None: + self._validate_key(record_type, record_key) + payload = self._encrypt(record_type, record_key, value) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + f"INSERT INTO {self.RECORD_TABLE} (record_type, record_key, encrypted_value) " + "VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE encrypted_value=VALUES(encrypted_value)", + (record_type, record_key, payload), + ) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError() from exc + finally: + connection.close() + + def insert(self, record_type: str, record_key: str, value: str) -> bool: + """Insert once; return False if another process already inserted it.""" + self._validate_key(record_type, record_key) + payload = self._encrypt(record_type, record_key, value) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + f"INSERT INTO {self.RECORD_TABLE} " + "(record_type, record_key, encrypted_value) VALUES (%s, %s, %s)", + (record_type, record_key, payload), + ) + connection.commit() + return True + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + return False + raise DatabaseError() from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError() from exc + finally: + connection.close() + + def delete(self, record_type: str, record_key: str) -> None: + self._validate_key(record_type, record_key) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + f"DELETE FROM {self.RECORD_TABLE} WHERE record_type=%s AND record_key=%s", + (record_type, record_key), + ) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError() from exc + finally: + connection.close() + + def list(self, record_type: str) -> dict[str, str]: + self._validate_key(record_type, "x") + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + f"SELECT record_key, encrypted_value FROM {self.RECORD_TABLE} WHERE record_type=%s", + (record_type,), + ) + rows = cursor.fetchall() + return { + row["record_key"]: self._decrypt( + record_type, row["record_key"], row["encrypted_value"], + ) for row in rows + } + except pymysql.MySQLError as exc: + raise DatabaseError() from exc + finally: + connection.close() + + def get_secret(self, name: str) -> str | None: + return self.get("secret", name) + + def set_secret(self, name: str, value: str) -> None: + self.set("secret", name, value) + + def delete_secret(self, name: str) -> None: + self.delete("secret", name) + + def get_value(self, name: str) -> str | None: + return self.get("value", name) + + def set_value(self, name: str, value: str) -> None: + self.set("value", name, value) + + def delete_value(self, name: str) -> None: + self.delete("value", name) + + +class DatabasePanelState(PanelState): + """Initial user in MariaDB; the one-time token remains a local file.""" + + def __init__(self, data_dir: Path, store: DatabaseStore, users: Any) -> None: + super().__init__(data_dir) + self.store = store + self.users = users + from .ssh_keys import DatabaseSSHKeyStore + self.ssh_keys = DatabaseSSHKeyStore(store) + + def admin(self) -> tuple[str, str] | None: + raise RuntimeError("Database-backed authentication must use state.users") + + def setup_required(self) -> bool: + return not self.users.has_users() + + def create_admin(self, token: str, username: str, password: str, + email: str | None = None) -> str: + if not isinstance(username, str) or not _USERNAME.fullmatch(username): + raise SetupError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符") + if not isinstance(password, str) or len(password) < 12 or len(password) > 1024: + raise SetupError("密码长度须在 12 至 1024 位之间") + with self._setup_lock(): + if not self.setup_required(): + raise SetupError("初始用户已创建", 409) + try: + expected = self._read_token() + except FileNotFoundError as exc: + raise SetupError("初始化口令不可用,请重新启动面板并查看启动终端输出", 503) from exc + if not isinstance(token, str) or not hmac.compare_digest(token, expected): + raise SetupError("初始化口令无效", 403) + self.users.create_initial_user(username, password, email) + self.token_file.unlink(missing_ok=True) + self._fsync_directory() + return username + + +class DatabaseTemplateStore: + """Cloud-image catalog records stored independently in MariaDB.""" + + def __init__(self, store: DatabaseStore) -> None: + self.store = store + + def list(self, scope: str) -> list[dict]: + prefix = f"{scope}:" + records = [] + for key, payload in self.store.list("template").items(): + if not key.startswith(prefix): + continue + try: + record = json.loads(payload) + except (TypeError, ValueError) as exc: + raise TemplateError("数据库模板记录损坏", 500) from exc + if not isinstance(record, dict): + raise TemplateError("数据库模板记录损坏", 500) + records.append(record) + return records + + def get(self, scope: str, template_id: str) -> dict: + for record in self.list(scope): + if record.get("id") == template_id: + return record + raise TemplateError("模板不存在或不属于当前宿主机", 404) + + def add(self, scope: str, record: dict) -> dict: + if not isinstance(record, dict) or not isinstance(record.get("id"), str): + raise TemplateError("模板记录无效") + key = f"{scope}:{record['id']}" + if any(row.get("id") != record["id"] + and row.get("name", "").casefold() == record["name"].casefold() + for row in self.list(scope)): + raise TemplateError("当前宿主机已有同名云镜像模板", 409) + if not self.store.insert("template", key, json.dumps( + record, ensure_ascii=False, separators=(",", ":"))): + raise TemplateError("此云镜像已导入", 409) + return record + + def rename(self, scope: str, template_id: str, name: str) -> dict: + name = validate_template_name(name) + record = self.get(scope, template_id) + if any(row.get("id") != template_id + and row.get("name", "").casefold() == name.casefold() + for row in self.list(scope)): + raise TemplateError("当前宿主机已有同名云镜像模板", 409) + updated = {**record, "name": name} + self.store.set("template", f"{scope}:{template_id}", json.dumps( + updated, ensure_ascii=False, separators=(",", ":"))) + return updated + + +class DatabaseStagedHost(StagedHost): + def __init__(self, staged: StagedHost, wrapper_path: Path, + private_key_passphrase: str) -> None: + super().__init__(staged.path, staged.metadata, staged.tested) + self.wrapper_path = wrapper_path + # The staged secret is process-local until a successful save; the + # complete host record is encrypted by DatabaseStore at rest. + self._private_key_passphrase = private_key_passphrase + + @property + def libvirt_uri(self) -> str: + return f"{LIBVIRT_URI}&command={quote(str(self.wrapper_path), safe='/')}" + + +class _DatabaseSSHAgentSession(SSHAgentSession): + """Keep the no-secret askpass executable off possibly-noexec tmpfs.""" + + def __init__(self, generation: Path, key_path: Path, passphrase: str, + helper_dir: Path) -> None: + self._helper_dir = helper_dir + super().__init__(generation, key_path, passphrase) + + def _create_helper(self) -> Path: + helper = self._helper_dir / ("askpass-" + secrets.token_hex(8)) + _write_private(helper, _ASKPASS_SOURCE) + helper.chmod(0o700) + self._helper_path = helper + return helper + + +class DatabaseRemoteHostManager(RemoteHostManager): + """Existing SSH workflow, with encrypted DB persistence and tmpfs keys.""" + + @staticmethod + def _process_start_ticks(pid: int) -> str | None: + """Linux process birth marker, to distinguish a recycled PID.""" + try: + content = Path(f"/proc/{pid}/stat").read_text(encoding="ascii") + fields = content[content.rfind(")") + 2:].split() + return fields[19] # /proc stat field 22; tail starts at field 3. + except (FileNotFoundError, IndexError, OSError, ValueError): + return None + + @classmethod + def _clean_stale_runtime(cls, parent: Path) -> None: + """Remove only our private, marked dirs whose exact owner process died.""" + try: + entries = list(parent.iterdir()) + except OSError: + return + for entry in entries: + match = _RUNTIME_NAME.fullmatch(entry.name) + if match is None: + continue + try: + info = entry.lstat() + if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() + or stat.S_IMODE(info.st_mode) != 0o700): + continue + marker = entry / ".owner" + marker_info = marker.lstat() + if (not stat.S_ISREG(marker_info.st_mode) + or marker_info.st_uid != os.geteuid() + or stat.S_IMODE(marker_info.st_mode) != 0o600): + continue + owner = marker.read_text(encoding="ascii").strip().split(":") + pid = int(match.group(1)) + if len(owner) != 2 or owner[0] != str(pid) or not owner[1].isdigit(): + continue + birth = cls._process_start_ticks(pid) + if birth is None or birth != owner[1]: + shutil.rmtree(entry) + except (OSError, UnicodeError, ValueError): + # Never prune a directory whose ownership cannot be proven. + continue + + def __init__( + self, store: DatabaseStore, data_dir: Path, *, ssh_binary: str = "ssh", + runtime_parent: Path | None = None, **kwargs: Any, + ) -> None: + self.store = store + if Path(data_dir).is_symlink(): + raise RemoteHostError("面板数据目录不能是符号链接", 500) + self._persistent_dir = Path(data_dir).resolve() + self._persistent_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + if stat.S_IMODE(self._persistent_dir.stat().st_mode) & 0o077: + raise RemoteHostError("面板数据目录权限不安全", 500) + wrapper_dir = self._persistent_dir / "runtime-wrappers" + if wrapper_dir.is_symlink(): + raise RemoteHostError("SSH 包装器目录不能是符号链接", 500) + wrapper_dir.mkdir(mode=0o700, exist_ok=True) + if stat.S_IMODE(wrapper_dir.stat().st_mode) & 0o077: + raise RemoteHostError("SSH 包装器目录权限不安全", 500) + self._wrapper_dir = wrapper_dir + self._wrapper_paths: set[Path] = set() + self._passphrase_saved = False + self._last_background_unlock_attempt = float("-inf") + if runtime_parent is None: + if sys.platform == "linux": + runtime_parent = Path("/dev/shm") + if not runtime_parent.is_dir() or not os.access(runtime_parent, os.W_OK): + raise RemoteHostError("/dev/shm 不可用,无法安全存放临时 SSH 密钥", 500) + else: + # A disk-backed fallback would leave the decrypted SSH key in + # data/ after an unclean shutdown. Tests may supply an + # explicit isolated runtime parent, but production requires + # the Linux tmpfs path above. + raise RemoteHostError("数据库模式仅支持 Linux 的 /dev/shm 临时密钥目录", 500) + if sys.platform == "linux": + self._clean_stale_runtime(Path(runtime_parent)) + # SSHAgentSession requires a socket path under 100 bytes. The fixed + # `generations/gen-.../agent-...sock` suffix leaves only a tiny prefix + # budget under /dev/shm on Linux, so mkdtemp's eight-byte suffix is + # too long for systems with seven-digit PIDs. + self._runtime_dir = None + for _attempt in range(16): + candidate = Path(runtime_parent) / f"v{os.getpid()}-{secrets.token_hex(2)}" + try: + candidate.mkdir(mode=0o700) + except FileExistsError: + continue + self._runtime_dir = candidate + break + if self._runtime_dir is None: + raise RemoteHostError("无法创建独立的 SSH 临时目录", 500) + self._runtime_dir.chmod(0o700) + if sys.platform == "linux": + birth = self._process_start_ticks(os.getpid()) + if birth is None: + shutil.rmtree(self._runtime_dir, ignore_errors=True) + raise RemoteHostError("无法确认面板进程身份,拒绝存放 SSH 密钥", 500) + _write_private(self._runtime_dir / ".owner", + f"{os.getpid()}:{birth}\n".encode("ascii")) + try: + kwargs.setdefault( + "agent_factory", + lambda generation, key_path, passphrase: _DatabaseSSHAgentSession( + generation, key_path, passphrase, self._wrapper_dir, + ), + ) + super().__init__( + self._runtime_dir, ssh_binary=ssh_binary, + ssh_user_config_path=self._runtime_dir / ".ssh" / "config", + **kwargs, + ) + self._restore_current() + except BaseException: + shutil.rmtree(self._runtime_dir, ignore_errors=True) + for wrapper in self._wrapper_paths: + wrapper.unlink(missing_ok=True) + raise + + def _wrapper_for(self, generation: Path) -> Path: + return self._wrapper_dir / generation.name + + def _write_wrapper(self, generation: Path) -> Path: + destination = self._wrapper_for(generation) + source = ( + "#!/usr/bin/env python3\n" + "import os\nimport sys\n" + f"os.execvp({self.ssh_binary!r}, " + f"[{self.ssh_binary!r}, '-F', {str(generation / 'config')!r}, *sys.argv[1:]])\n" + ) + _write_private(destination, source.encode("ascii")) + destination.chmod(0o700) + self._wrapper_paths.add(destination) + return destination + + def _saved_host_record(self) -> dict[str, Any] | None: + raw = self.store.get("host", "current") + if raw is None: + return None + try: + record = json.loads(raw) + if not isinstance(record, dict): + raise ValueError("Invalid host record") + passphrase = record.get("private_key_passphrase", "") + if not isinstance(passphrase, str): + raise ValueError("Invalid host passphrase") + return record + except (TypeError, ValueError) as exc: + raise RemoteHostError("数据库宿主机配置损坏", 500) from exc + + def stage(self, profile, confirmed_fingerprint: str) -> DatabaseStagedHost: + if isinstance(profile, Mapping): + try: + profile = HostProfile(**profile) + except (TypeError, ValueError) as exc: + raise RemoteHostError("宿主机配置字段无效") from exc + if not isinstance(profile, HostProfile): + raise RemoteHostError("宿主机配置字段无效") + if not profile.private_key_passphrase: + saved = self._saved_host_record() + if saved is not None and saved.get("private_key_passphrase"): + try: + saved_key = _validate_private_key(saved["private_key"]) + requested_key = (_validate_private_key(profile.private_key) + if profile.private_key else saved_key) + except (KeyError, TypeError, UnicodeError) as exc: + raise RemoteHostError("数据库宿主机配置损坏", 500) from exc + if hmac.compare_digest(requested_key, saved_key): + profile = replace(profile, private_key_passphrase= + saved["private_key_passphrase"]) + staged = super().stage(profile, confirmed_fingerprint) + try: + wrapper = self._write_wrapper(staged.path) + except BaseException: + super().abort(staged) + raise + return DatabaseStagedHost(staged, wrapper, profile.private_key_passphrase) + + def abort(self, staged: StagedHost) -> None: + super().abort(staged) + wrapper = self._wrapper_for(staged.path) + wrapper.unlink(missing_ok=True) + self._wrapper_paths.discard(wrapper) + + def _staged_record(self, staged: StagedHost) -> dict: + try: + return { + "metadata": staged.metadata, + "private_key": (staged.path / "id_private").read_text(encoding="ascii"), + "known_hosts": (staged.path / "known_hosts").read_text(encoding="ascii"), + "identity_public": ( + (staged.path / "identity.pub").read_text(encoding="ascii") + if (staged.path / "identity.pub").exists() else None + ), + "private_key_passphrase": ( + staged._private_key_passphrase + if staged.metadata["private_key_encrypted"] else "" + ), + } + except (OSError, UnicodeError) as exc: + raise RemoteHostError("暂存宿主机密钥无法读取", 500) from exc + + def commit(self, staged: StagedHost) -> dict[str, Any]: + self._check_staged(staged) + if not staged.tested: + raise RemoteHostError("保存前必须先测试宿主机连接", 409) + # Check the runtime activation preconditions before committing DB. + self._ensure_user_ssh_config() + previous = self.store.get("host", "current") + record = self._staged_record(staged) + next_passphrase_saved = bool(record["metadata"]["private_key_encrypted"] + and record["private_key_passphrase"]) + payload = json.dumps(record, ensure_ascii=False, + separators=(",", ":")) + self.store.set("host", "current", payload) + previous_passphrase_saved = self._passphrase_saved + self._passphrase_saved = next_passphrase_saved + try: + return super().commit(staged) + except BaseException: + self._passphrase_saved = previous_passphrase_saved + if previous is None: + self.store.delete("host", "current") + else: + self.store.set("host", "current", previous) + raise + + def _restore_current(self) -> None: + record = self._saved_host_record() + if record is None: + return + try: + metadata = record["metadata"] + host = _validate_host(metadata["host"]) + port = _validate_port(metadata["port"]) + storage_pool = _validate_pool_selector(metadata["storage_pool"], "磁盘池") + iso_pool = _validate_pool_selector(metadata["iso_pool"], "ISO 池") + default_network = _validate_network_selector(metadata["default_network"]) + region = _validate_region(metadata.get("region", "")) + public_pool = validate_public_pool( + metadata.get("public_pool_cidr", ""), + metadata.get("public_gateway", ""), + metadata.get("public_dns_servers", []), + metadata.get("public_reserved_ips", []), + host, + metadata.get("public_vm_prefix"), + ) + private_key = _validate_private_key(record["private_key"]) + known_hosts = record["known_hosts"].strip() + key_type, encoded = _key_parts(known_hosts) + if (not known_hosts.startswith(SSH_ALIAS + " ") + or metadata["fingerprint"] != _fingerprint(f"{key_type} {encoded}")): + raise ValueError("Host key mismatch") + encrypted = bool(metadata["private_key_encrypted"]) + identity_public = record["identity_public"] + passphrase = record.get("private_key_passphrase", "") + if encrypted and (not isinstance(identity_public, str) + or len(identity_public.split()) < 2): + raise ValueError("Encrypted host identity is missing") + except (KeyError, TypeError, ValueError, RemoteHostError, UnicodeError) as exc: + raise RemoteHostError("数据库宿主机配置损坏", 500) from exc + + self._ensure_storage() + generation = self.data_dir / "generations" / ("gen-" + secrets.token_hex(16)) + generation.mkdir(mode=0o700) + try: + _write_private(generation / "id_private", private_key) + _write_private(generation / "known_hosts", (known_hosts + "\n").encode("ascii")) + identity_path = generation / "id_private" + if encrypted: + _write_private(generation / "identity.pub", identity_public.encode("ascii")) + identity_path = generation / "identity.pub" + config_text = ( + f"Host {SSH_ALIAS}\n" + f" HostName {host}\n" + f" Port {port}\n" + " User root\n" + f" IdentityFile {_quoted_path(identity_path)}\n" + f" UserKnownHostsFile {_quoted_path(generation / 'known_hosts')}\n" + " GlobalKnownHostsFile /dev/null\n" + f" HostKeyAlias {SSH_ALIAS}\n" + " HostKeyAlgorithms ssh-ed25519\n" + " StrictHostKeyChecking yes\n" + " VerifyHostKeyDNS no\n" + " BatchMode yes\n" + " IdentitiesOnly yes\n" + " IdentityAgent none\n" + " PreferredAuthentications publickey\n" + " PasswordAuthentication no\n" + " KbdInteractiveAuthentication no\n" + " GSSAPIAuthentication no\n" + " ForwardAgent no\n" + " ProxyCommand none\n" + " ProxyJump none\n" + " CanonicalizeHostname no\n" + " ControlMaster no\n" + " ControlPath none\n" + " UpdateHostKeys no\n" + " RequestTTY no\n" + " ServerAliveInterval 15\n" + " ServerAliveCountMax 2\n" + " ConnectTimeout 10\n" + ) + _write_private(generation / "config", config_text.encode("ascii")) + _write_private(generation / "profile.json", json.dumps( + {**metadata, "host": host, "port": port, + "storage_pool": storage_pool, "iso_pool": iso_pool, + "default_network": default_network, "region": region, + **public_pool}, + ensure_ascii=False, + ).encode("utf-8")) + wrapper = self._write_wrapper(generation) + self._ensure_user_ssh_config() + temporary_link = self.data_dir / (".current-" + secrets.token_hex(8)) + temporary_link.symlink_to(generation) + os.replace(temporary_link, self.data_dir / "current") + assert wrapper.exists() + self._passphrase_saved = bool(encrypted and passphrase) + if encrypted and passphrase: + try: + super().unlock_current(passphrase) + except RemoteHostError: + # Keep the panel available for an operator to re-save a + # corrected key/phrase. Never print the secret or SSH output. + LOG.warning("saved remote SSH key could not be auto-unlocked") + except BaseException: + shutil.rmtree(generation, ignore_errors=True) + raise + + @property + def libvirt_uri(self) -> str: + generation = self._current_generation() + if generation is None: + return LIBVIRT_URI + return f"{LIBVIRT_URI}&command={quote(str(self._wrapper_for(generation)), safe='/')}" + + def current(self) -> dict[str, Any] | None: + profile = super().current() + if profile is None: + return None + profile["private_key_passphrase_saved"] = self._passphrase_saved + profile["libvirt_uri"] = self.libvirt_uri + return profile + + def current_for_background(self) -> dict[str, Any] | None: + """Recover a lost SSH agent so unattended metric sampling can resume.""" + profile = self.current() + if profile is None or not profile["key_locked"] or not self._passphrase_saved: + return profile + with self._lock: + profile = self.current() + if profile is None or not profile["key_locked"]: + return profile + now = time.monotonic() + if now - self._last_background_unlock_attempt < 60: + return profile + self._last_background_unlock_attempt = now + record = self._saved_host_record() + passphrase = record.get("private_key_passphrase", "") if record else "" + if not passphrase: + return profile + try: + return super().unlock_current(passphrase) + except RemoteHostError: + LOG.warning("saved remote SSH key could not be unlocked for background metrics") + return self.current() + + def close(self) -> None: + super().close() + shutil.rmtree(self._runtime_dir, ignore_errors=True) + for wrapper in self._wrapper_paths: + wrapper.unlink(missing_ok=True) + self._wrapper_paths.clear() + + +def make_components( + data_dir: Path, db_config: Mapping[str, Any], master_key: bytes, + ssh_binary: str = "ssh", +) -> tuple[DatabasePanelState, DatabaseRemoteHostManager, DatabaseTemplateStore, DatabaseStore]: + """Create ready-to-use DB-backed application components.""" + from .users import DatabaseUserStore + + store = DatabaseStore(db_config, master_key) + state = DatabasePanelState(data_dir, store, DatabaseUserStore(store, master_key)) + manager = DatabaseRemoteHostManager(store, data_dir, ssh_binary=ssh_binary) + templates = DatabaseTemplateStore(store) + return state, manager, templates, store diff --git a/engine/virsh_panel/database_bootstrap.py b/engine/virsh_panel/database_bootstrap.py new file mode 100644 index 00000000..b5acc815 --- /dev/null +++ b/engine/virsh_panel/database_bootstrap.py @@ -0,0 +1,237 @@ +"""Private, encrypted bootstrap configuration for the panel database. + +The database cannot contain its own connection password. The only durable +local state is therefore a 0600 encryption key, an encrypted connection +document and the one-time setup token (until an administrator is created). +""" + +from __future__ import annotations + +import base64 +import fcntl +import hmac +import ipaddress +import json +import os +import re +import secrets +import stat +import tempfile +import threading +from contextlib import contextmanager +from pathlib import Path +from typing import Callable, Mapping, TypeVar + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + +_AAD = b"virsh-panel/database-bootstrap/v1" +_DATABASE_NAME = re.compile(r"[A-Za-z0-9_]{1,64}\Z") +_DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") +_T = TypeVar("_T") + + +class DatabaseSetupError(Exception): + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +def validate_database_config(config: Mapping[str, object]) -> dict[str, object]: + """Normalize user-entered connection parameters without SQL interpolation.""" + host = config.get("host") + port = config.get("port") + database = config.get("database") + username = config.get("username") + password = config.get("password") + if not isinstance(host, str) or not host or len(host) > 253 or host != host.strip(): + raise DatabaseSetupError("数据库地址格式无效") + try: + ipaddress.ip_address(host) + except ValueError: + if not all(_DNS_LABEL.fullmatch(label) for label in host.split(".")): + raise DatabaseSetupError("数据库地址必须是 IP 或 DNS 名称") from None + host = host.lower() + if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: + raise DatabaseSetupError("数据库端口必须介于 1 到 65535") + if not isinstance(database, str) or not _DATABASE_NAME.fullmatch(database): + raise DatabaseSetupError("数据库名仅支持 1 至 64 位字母、数字和下划线") + if (not isinstance(username, str) or not 1 <= len(username) <= 128 + or any(ord(char) < 33 or ord(char) == 127 for char in username)): + raise DatabaseSetupError("数据库用户名格式无效") + if not isinstance(password, str) or not 1 <= len(password) <= 1024 or "\x00" in password: + raise DatabaseSetupError("数据库密码不能为空或格式无效") + return { + "host": host, "port": port, "database": database, + "username": username, "password": password, + } + + +class DatabaseBootstrap: + def __init__(self, data_dir: Path) -> None: + requested = Path(data_dir) + if requested.is_symlink(): + raise ValueError("面板数据目录不能是符号链接") + self.data_dir = requested.resolve() + self.data_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + info = self.data_dir.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_mode & 0o077: + raise ValueError("面板数据目录权限必须为 0700") + self.config_file = self.data_dir / "database-config.json" + self.key_file = self.data_dir / "master.key" + self.token_file = self.data_dir / "setup-token" + self.lock_file = self.data_dir / ".database.lock" + self._lock = threading.RLock() + + @staticmethod + def _read_private(path: Path) -> bytes: + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise ValueError(f"敏感配置文件权限必须为 0600:{path.name}") + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(path, flags) + try: + return os.read(descriptor, 1024 * 1024 + 1) + finally: + os.close(descriptor) + + def _sync_directory(self) -> None: + descriptor = os.open(self.data_dir, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + def _write_private(self, path: Path, content: bytes) -> None: + descriptor, raw_path = tempfile.mkstemp(prefix=f".{path.name}-", dir=self.data_dir) + try: + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, "wb") as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + os.replace(raw_path, path) + self._sync_directory() + finally: + if os.path.exists(raw_path): + os.unlink(raw_path) + + @contextmanager + def _exclusive(self): + with self._lock: + flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(self.lock_file, flags, 0o600) + try: + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise ValueError("数据库初始化锁文件权限必须为 0600") + fcntl.flock(descriptor, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(descriptor, fcntl.LOCK_UN) + finally: + os.close(descriptor) + + def configured(self) -> bool: + return self.config_file.exists() + + def ensure_token(self) -> str: + """Create once; database and administrator setup share the same token.""" + with self._exclusive(): + try: + token = self._read_private(self.token_file).decode("ascii").strip() + if len(token) < 32: + raise ValueError("初始化令牌文件无效") + return token + except FileNotFoundError: + token = secrets.token_urlsafe(32) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(self.token_file, flags, 0o600) + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write((token + "\n").encode("ascii")) + stream.flush() + os.fsync(stream.fileno()) + self._sync_directory() + except BaseException: + self.token_file.unlink(missing_ok=True) + raise + return token + + def master_key(self, *, create: bool = False) -> bytes: + try: + key = self._read_private(self.key_file) + except FileNotFoundError: + if not create: + raise ValueError("数据库加密主密钥不存在") from None + key = secrets.token_bytes(32) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(self.key_file, flags, 0o600) + except FileExistsError: + return self.master_key() + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write(key) + stream.flush() + os.fsync(stream.fileno()) + self._sync_directory() + except BaseException: + self.key_file.unlink(missing_ok=True) + raise + if len(key) != 32: + raise ValueError("数据库加密主密钥无效") + return key + + def load_config(self) -> dict[str, object] | None: + try: + content = self._read_private(self.config_file) + except FileNotFoundError: + return None + try: + envelope = json.loads(content) + if envelope.get("version") != 1: + raise ValueError("版本无效") + nonce = base64.b64decode(envelope["nonce"], validate=True) + ciphertext = base64.b64decode(envelope["ciphertext"], validate=True) + if len(nonce) != 12 or len(ciphertext) > 4096: + raise ValueError("密文无效") + raw = AESGCM(self.master_key()).decrypt(nonce, ciphertext, _AAD) + return validate_database_config(json.loads(raw)) + except (KeyError, TypeError, ValueError, InvalidTag) as exc: + raise ValueError("数据库连接配置损坏或加密主密钥不匹配") from exc + + def configure( + self, config: Mapping[str, object], setup_token: str, + connect: Callable[[dict[str, object], bytes], _T], + ) -> _T: + """Verify token and DB access, then atomically commit encrypted config.""" + normalized = validate_database_config(config) + with self._exclusive(): + if self.configured(): + raise DatabaseSetupError("数据库已经配置", 409) + try: + expected = self._read_private(self.token_file).decode("ascii").strip() + except FileNotFoundError as exc: + raise DatabaseSetupError("初始化令牌不可用,请重启面板后查看终端输出", 503) from exc + if (not isinstance(setup_token, str) + or not hmac.compare_digest(setup_token, expected)): + raise DatabaseSetupError("初始化令牌无效", 403) + key = self.master_key(create=True) + result = connect(normalized, key) + nonce = secrets.token_bytes(12) + plaintext = json.dumps(normalized, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + encrypted = AESGCM(key).encrypt(nonce, plaintext, _AAD) + envelope = { + "version": 1, + "nonce": base64.b64encode(nonce).decode("ascii"), + "ciphertext": base64.b64encode(encrypted).decode("ascii"), + } + self._write_private( + self.config_file, + (json.dumps(envelope, separators=(",", ":")) + "\n").encode("ascii"), + ) + return result diff --git a/engine/virsh_panel/engine_context.py b/engine/virsh_panel/engine_context.py new file mode 100644 index 00000000..4fc7902d --- /dev/null +++ b/engine/virsh_panel/engine_context.py @@ -0,0 +1,213 @@ +"""PHP-owned identities, stable host namespaces, and separate engine databases.""" +from __future__ import annotations + +import hashlib +import json +from contextvars import ContextVar +from dataclasses import dataclass +from types import SimpleNamespace +from typing import Any + +from .auth import Session +from .database import (DatabaseError, DatabaseRemoteHostManager, DatabaseStore, + DatabaseTemplateStore, _METRIC_SCHEMA, _SCHEMA, pymysql) + + +TRUSTED_ACTOR: ContextVar[dict | None] = ContextVar("cloud_trusted_actor", default=None) + + +def actor() -> dict: + value = TRUSTED_ACTOR.get() + if value is None: + raise PermissionError("Missing authenticated PHP actor") + return value + + +def actor_session() -> Session: + value = actor() + return Session("internal", f"php:{value['user_id']}", "", float("inf"), value["user_id"]) + + +def actor_account(session: Session) -> dict: + value = actor() + if session.user_id != value["user_id"]: + raise PermissionError("Actor does not match request") + return {"id": value["user_id"], "username": f"php:{value['user_id']}", + "admin": value["is_admin"], "approved": True, "email_verified": True} + + +class MainStore(DatabaseStore): + RECORD_TABLE = "engine_records" + + def _initialize_schema(self) -> None: + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute(_SCHEMA.replace("panel_records", self.RECORD_TABLE)) + cursor.execute("""CREATE TABLE IF NOT EXISTS engine_request_nonces ( + nonce VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + expires_at BIGINT UNSIGNED NOT NULL, + PRIMARY KEY(nonce), KEY nonce_expiry(expires_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""") + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法初始化引擎数据库") from exc + finally: + connection.close() + + def consume_nonce(self, nonce: str, expires_at: int, now: int) -> bool: + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("DELETE FROM engine_request_nonces WHERE expires_at < %s LIMIT 1000", (now,)) + cursor.execute("INSERT INTO engine_request_nonces(nonce,expires_at) VALUES(%s,%s)", + (nonce, expires_at)) + connection.commit() + return True + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + return False + raise DatabaseError() from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError() from exc + finally: + connection.close() + + +class LogStore(DatabaseStore): + METRIC_TABLE = "engine_vm_metric_samples" + + def _initialize_schema(self) -> None: + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute(_METRIC_SCHEMA.replace("vm_metric_samples", self.METRIC_TABLE)) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法初始化日志库的虚拟机指标表") from exc + finally: + connection.close() + + +class HostStore: + """One current profile per stable host ID, never one shared current host.""" + def __init__(self, store: Any, host_id: str): + self.store = store + self.prefix = hashlib.sha256(host_id.encode("ascii")).hexdigest() + ":" + + def _key(self, key: str) -> str: + return self.prefix + key + + def get(self, kind: str, key: str): + return self.store.get(kind, self._key(key)) + + def set(self, kind: str, key: str, value: str): + return self.store.set(kind, self._key(key), value) + + def insert(self, kind: str, key: str, value: str): + return self.store.insert(kind, self._key(key), value) + + def delete(self, kind: str, key: str): + return self.store.delete(kind, self._key(key)) + + def list(self, kind: str): + return {key[len(self.prefix):]: value for key, value in self.store.list(kind).items() + if key.startswith(self.prefix)} + + def get_value(self, key: str): + return self.get("value", key) + + def set_value(self, key: str, value: str): + return self.set("value", key, value) + + def delete_value(self, key: str): + return self.delete("value", key) + + def get_secret(self, key: str): + return self.get("secret", key) + + def set_secret(self, key: str, value: str): + return self.set("secret", key, value) + + +class ExternalOwnership: + """Immutable PHP subject -> host/UUID owner mapping, with no users FK.""" + def __init__(self, store: HostStore): + self.store = store + + @staticmethod + def _key(scope: str, vm_id: str) -> str: + return f"{scope}.{vm_id}" + + def get_by_id(self, user_id: int): + value = actor() + return actor_account(actor_session()) if value["user_id"] == user_id else None + + def owns_vm(self, scope: str, vm_id: str, user_id: int) -> bool: + raw = self.store.get("vm_owner", self._key(scope, vm_id)) + return raw is not None and json.loads(raw)["user_id"] == user_id + + def assign_vm(self, scope: str, vm_id: str, user_id: int) -> None: + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("External owner must be a positive PHP user ID") + key = self._key(scope, vm_id) + payload = json.dumps({"user_id": user_id}, separators=(",", ":")) + if not self.store.insert("vm_owner", key, payload): + if not self.owns_vm(scope, vm_id, user_id): + raise DatabaseError("虚拟机已有其他归属,不能重复分配") + + def list_owned_vm_ids(self, scope: str, user_id: int) -> set[str]: + prefix = scope + "." + return {key[len(prefix):] for key, raw in self.store.list("vm_owner").items() + if key.startswith(prefix) and json.loads(raw)["user_id"] == user_id} + + def delete_vm_owner(self, scope: str, vm_id: str) -> None: + self.store.delete("vm_owner", self._key(scope, vm_id)) + + +class StableHostManager(DatabaseRemoteHostManager): + def __init__(self, store, data_dir, *, host_id: str, **kwargs): + self.host_id = host_id + super().__init__(store, data_dir, **kwargs) + + def current(self): + profile = super().current() + if profile is not None: + profile["host_id"] = self.host_id + return profile + + def commit(self, staged): + profile = super().commit(staged) + profile["host_id"] = self.host_id + return profile + + def unlock_current(self, passphrase): + profile = super().unlock_current(passphrase) + profile["host_id"] = self.host_id + return profile + + def current_for_background(self): + profile = super().current_for_background() + if profile is not None: + profile["host_id"] = self.host_id + return profile + + +@dataclass +class EngineComponents: + state: Any + manager: Any + templates: Any + store: Any + metric_store: Any + + @classmethod + def for_host(cls, store, log_store, host_id, data_dir): + scoped = HostStore(store, host_id) + state = SimpleNamespace(users=ExternalOwnership(scoped)) + manager = StableHostManager(scoped, data_dir, host_id=host_id) + return cls(state, manager, DatabaseTemplateStore(scoped), scoped, log_store) diff --git a/engine/virsh_panel/engine_security.py b/engine/virsh_panel/engine_security.py new file mode 100644 index 00000000..a7ee7d15 --- /dev/null +++ b/engine/virsh_panel/engine_security.py @@ -0,0 +1,100 @@ +"""Non-browser HMAC transport: signed actors, payloads, time and replay defense.""" +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import re +import secrets +import time + + +class EngineAuthError(Exception): + def __init__(self, message="内部服务认证失败", status=401): + super().__init__(message) + self.status = status + + +def canonical(method: str, target: str, digest: str, timestamp: str, + nonce: str, encoded_actor: str) -> bytes: + return "\n".join((method.upper(), target, digest, timestamp, nonce, encoded_actor)).encode("utf-8") + + +def decode_secret(encoded: str) -> bytes: + try: + value = base64.b64decode(encoded, validate=True) + except (ValueError, TypeError) as exc: + raise ValueError("Engine service secret must be base64-encoded 32 bytes") from exc + if len(value) != 32: + raise ValueError("Engine service secret must be base64-encoded 32 bytes") + return value + + +def encode_actor(value: dict) -> str: + return base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":"), + ensure_ascii=True).encode()).decode().rstrip("=") + + +def signed_headers(secret: bytes, method: str, target: str, body: bytes, actor: dict, + *, timestamp: int | None = None, nonce: str | None = None) -> dict: + timestamp_raw = str(int(time.time()) if timestamp is None else timestamp) + nonce = nonce or secrets.token_urlsafe(24) + encoded = encode_actor(actor) + digest = hashlib.sha256(body).hexdigest() + signature = hmac.new(secret, canonical(method, target, digest, timestamp_raw, nonce, encoded), + hashlib.sha256).hexdigest() + return {"X-Cloud-Timestamp": timestamp_raw, "X-Cloud-Nonce": nonce, + "X-Cloud-Actor": encoded, "X-Cloud-Signature": signature} + + +def parse_actor(encoded: str) -> dict: + if not encoded or len(encoded) > 8192 or not re.fullmatch(r"[A-Za-z0-9_-]+", encoded): + raise EngineAuthError() + try: + raw = base64.b64decode(encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True) + value = json.loads(raw) + except (ValueError, UnicodeError) as exc: + raise EngineAuthError() from exc + if not isinstance(value, dict): + raise EngineAuthError() + user_id = value.get("user_id") + if isinstance(user_id, bool) or not isinstance(user_id, int) or not 1 <= user_id < 2**63: + raise EngineAuthError() + for key in ("is_admin", "is_super_admin", "can_manage"): + if not isinstance(value.get(key), bool): + raise EngineAuthError() + if value["is_super_admin"] and not value["is_admin"]: + raise EngineAuthError() + for key in ("can_provision",): + if key in value and not isinstance(value[key], bool): + raise EngineAuthError() + if "operation_id" in value and not re.fullmatch(r"[A-Za-z0-9_-]{8,80}", str(value["operation_id"])): + raise EngineAuthError() + session_id = value.get("session_id", "") + if not isinstance(session_id, str) or len(session_id) > 256 or any(ord(c) < 33 for c in session_id): + raise EngineAuthError() + return value + + +def authenticate(headers: dict, secret: bytes, method: str, target: str, + digest: str, nonce_store, *, now: int | None = None) -> dict: + now = int(time.time()) if now is None else now + timestamp_raw = headers.get("x-cloud-timestamp", "") + nonce = headers.get("x-cloud-nonce", "") + encoded_actor = headers.get("x-cloud-actor", "") + signature = headers.get("x-cloud-signature", "") + if (not re.fullmatch(r"[0-9]{1,12}", timestamp_raw) + or abs(now - int(timestamp_raw)) > 60 + or not re.fullmatch(r"[A-Za-z0-9_-]{16,128}", nonce) + or not re.fullmatch(r"[0-9a-f]{64}", signature) + or not re.fullmatch(r"[0-9a-f]{64}", digest)): + raise EngineAuthError() + expected = hmac.new(secret, canonical(method, target, digest, timestamp_raw, nonce, encoded_actor), + hashlib.sha256).hexdigest() + if not hmac.compare_digest(expected, signature): + raise EngineAuthError() + value = parse_actor(encoded_actor) + if not nonce_store.consume_nonce(nonce, now + 121, now): + raise EngineAuthError("内部服务请求已使用,已拒绝重放") + return value diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py new file mode 100644 index 00000000..cb573502 --- /dev/null +++ b/engine/virsh_panel/internal.py @@ -0,0 +1,655 @@ +"""Private PHP -> libvirt boundary. The legacy browser app is never exposed. + +Only allowlisted VM/host/template resources are dispatched to per-host services. +The public console endpoint accepts a short-lived, one-use ticket instead of a +PHP cookie, and rechecks the PHP session while the console remains connected. +""" +from __future__ import annotations + +import asyncio +import hashlib +import hmac +import json +import logging +import os +import re +import secrets +import stat +import time +import uuid +from contextlib import AsyncExitStack, suppress +from pathlib import Path +from urllib.parse import urlsplit +from urllib.request import (HTTPRedirectHandler, ProxyHandler, Request as URLRequest, + build_opener) + + +from .engine_context import (EngineComponents, LogStore, MainStore, TRUSTED_ACTOR, + actor_session) +from .engine_security import (EngineAuthError, authenticate, decode_secret, + signed_headers) + + +LOG = logging.getLogger(__name__) +HOST_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}\Z") +OP_ID = re.compile(r"[A-Za-z0-9_-]{8,80}\Z") +VM_ID = r"[0-9a-fA-F-]{36}" +JSON_LIMIT = 1024 * 1024 +READ_PATHS = ( + r"host", r"resources", r"vm-templates", r"rescue-templates", r"vms", + rf"vms/{VM_ID}(?:/metrics|/rescue)?", + r"(?:reinstall-jobs|rescue-jobs|vm-templates/import-jobs|rescue-templates/import-jobs)/[A-Za-z0-9_-]+", +) +WRITE_PATHS = { + "POST": (r"host/(?:scan|unlock|test)", r"vm-templates/import", r"rescue-templates", + r"vms", rf"vms/{VM_ID}/(?:actions|credential|reinstall|rescue|console-ticket)", + rf"vms/{VM_ID}/rescue/(?:exit|force-start)", r"reinstall-jobs/[A-Za-z0-9_-]+/ack-password"), + "PUT": (r"host",), + "PATCH": (r"vm-templates/[A-Za-z0-9_-]+",), + "DELETE": (rf"vms/{VM_ID}", r"rescue-templates/[A-Za-z0-9_-]+"), +} + + +class NoRedirects(HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + raise ValueError("Session introspection redirects are not allowed") + + +def private_config(path: Path) -> dict: + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_uid != os.geteuid(): + raise ValueError("引擎配置必须为运行用户拥有的普通 0600 文件") + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + try: + raw = os.read(descriptor, JSON_LIMIT + 1) + finally: + os.close(descriptor) + if len(raw) > JSON_LIMIT: + raise ValueError("引擎配置过大") + value = json.loads(raw) + if not isinstance(value, dict): + raise ValueError("引擎配置无效") + return value + + +def master_key(path: Path) -> bytes: + from .database_bootstrap import DatabaseBootstrap + if not path.is_absolute(): + raise ValueError("主密钥路径必须是绝对路径") + bootstrap = DatabaseBootstrap(path.parent) + bootstrap.key_file = path + return bootstrap.master_key(create=True) + + +class HostRegistry: + def __init__(self, config, store, log_store, *, factory=None): + self.config = config + self.store = store + self.log_store = log_store + self.factory = factory + self.components: dict[str, EngineComponents] = {} + self.apps = {} + self.lock = asyncio.Lock() + self.lifespans = AsyncExitStack() + + async def start(self): + await self.lifespans.__aenter__() + for host_id in await asyncio.to_thread(self.store.list, "engine_host"): + await self.get(host_id) + + async def close(self): + await self.lifespans.aclose() + + async def get(self, host_id: str): + if not HOST_ID.fullmatch(host_id): + raise EngineAuthError("宿主机标识无效", 400) + async with self.lock: + if host_id in self.apps: + return self.apps[host_id] + from .app import create_app + from .config import Settings + directory = Path(self.config["data_dir"]) / "hosts" / host_id + if self.factory is not None: + components, app = self.factory(host_id) + else: + components = await asyncio.to_thread(EngineComponents.for_host, + self.store, self.log_store, host_id, directory) + settings = Settings(data_dir=directory) + app = await asyncio.to_thread(create_app, settings, engine_components=components) + self.components[host_id] = components + await self.lifespans.enter_async_context(app.router.lifespan_context(app)) + self.apps[host_id] = app + return app + + +async def json_response(send, status: int, payload): + body = json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode() + await send({"type": "http.response.start", "status": status, + "headers": [(b"content-type", b"application/json"), (b"cache-control", b"no-store")]}) + await send({"type": "http.response.body", "body": body}) + + +def raw_target(scope) -> str: + path = scope.get("raw_path", scope["path"].encode("ascii")).decode("ascii") + query = scope.get("query_string", b"") + return path + ("?" + query.decode("ascii") if query else "") + + +def request_headers(scope): + values = {} + for key, value in scope.get("headers", []): + name = key.decode("ascii").lower() + if name.startswith("x-cloud-") and name in values: + raise EngineAuthError("重复的内部认证头") + values[name] = value.decode("latin-1") + return values + + +class EngineApplication: + def __init__(self, config, store, log_store, *, registry=None, introspection=None): + self.config = config + self.store = store + self.secret = decode_secret(config["service_secret"]) + self.registry = registry or HostRegistry(config, store, log_store) + self.introspection = introspection + self.active_operations: set[str] = set() + self.console_check_interval = 15 + + async def __call__(self, scope, receive, send): + if scope["type"] == "lifespan": + await self._lifespan(receive, send) + return + if scope["type"] == "websocket": + try: + await self._console(scope, receive, send) + except Exception: + LOG.warning("Engine console rejected because a dependency failed") + await send({"type": "websocket.close", "code": 4403}) + return + if scope["type"] != "http": + return + token = None + response_started = False + async def tracked_send(message): + nonlocal response_started + if message["type"] == "http.response.start": + response_started = True + await send(message) + try: + # Public reverse proxies must never forward these routes. Reject + # non-loopback peers even when they have spoofed forwarded headers. + client = scope.get("client") + if client and client[0] not in {"127.0.0.1", "::1", "testclient"}: + raise EngineAuthError("内部引擎仅接受本机服务请求", 403) + headers = request_headers(scope) + target = raw_target(scope) + upload = scope["method"] == "POST" and bool(re.fullmatch( + r"/internal/v1/hosts/[A-Za-z0-9_-]+/rescue-templates", scope["path"])) + if upload: + digest = headers.get("x-cloud-content-sha256", "") + delegated = await asyncio.to_thread(authenticate, headers, self.secret, + scope["method"], target, digest, self.store) + self._authorize_route(scope["method"], "rescue-templates", delegated) + checksum = hashlib.sha256() + validation = {"complete": False, "valid": False} + scope = {**scope, "engine_upload_validation": validation} + async def verified_receive(): + message = await receive() + if message["type"] == "http.request": + chunk = message.get("body", b"") + checksum.update(chunk) + if not message.get("more_body", False): + validation.update(complete=True, + valid=hmac.compare_digest(checksum.hexdigest(), digest)) + return message + child_receive = verified_receive + body = None + else: + chunks = [] + size = 0 + while True: + message = await receive() + if message["type"] == "http.disconnect": + return + chunk = message.get("body", b"") + size += len(chunk) + if size > JSON_LIMIT: + raise EngineAuthError("内部请求超过 1 MiB", 413) + chunks.append(chunk) + if not message.get("more_body", False): + break + body = b"".join(chunks) + delegated = await asyncio.to_thread(authenticate, headers, self.secret, + scope["method"], target, hashlib.sha256(body).hexdigest(), self.store) + delivered = False + async def replay_receive(): + nonlocal delivered + if not delivered: + delivered = True + return {"type": "http.request", "body": body, "more_body": False} + return await receive() + child_receive = replay_receive + token = TRUSTED_ACTOR.set(delegated) + await self._dispatch(scope, child_receive, tracked_send, body, delegated) + except EngineAuthError as exc: + if not response_started: + await json_response(send, exc.status, {"error": str(exc)}) + except Exception: + LOG.exception("Private engine request failed") + if not response_started: + await json_response(send, 503, {"error": "引擎服务暂时不可用,请检查引擎日志"}) + finally: + if token is not None: + TRUSTED_ACTOR.reset(token) + + @staticmethod + def _authorize_route(method: str, resource: str, delegated: dict): + paths = READ_PATHS if method == "GET" else WRITE_PATHS.get(method, ()) + if not any(re.fullmatch(pattern, resource) for pattern in paths): + raise EngineAuthError("内部资源不存在", 404) + administration = (resource.startswith("host") or resource.startswith("vm-templates/") + or resource.startswith("rescue-templates/")) + administration_write = method != "GET" and (administration or resource == "rescue-templates") + if administration and not delegated["is_admin"]: + raise EngineAuthError("仅管理员可访问此资源", 403) + if method != "GET" and not delegated["can_manage"]: + raise EngineAuthError("当前账户不允许操作", 403) + if administration_write and not delegated["is_super_admin"]: + raise EngineAuthError("仅超级管理员可修改宿主机和模版", 403) + + async def _dispatch(self, scope, receive, send, body, delegated): + path = scope["path"] + if scope["method"] == "POST" and path == "/internal/v1/hosts/scan": + if not delegated["is_super_admin"] or not delegated["can_manage"]: + raise EngineAuthError("仅超级管理员可以扫描宿主机", 403) + from .app import HostScanBody + from .remote_host import RemoteHostManager + from pydantic import ValidationError + try: + value = HostScanBody.model_validate_json(body) + except ValidationError as exc: + raise EngineAuthError("宿主机扫描参数无效", 422) from exc + manager = await asyncio.to_thread(RemoteHostManager, + Path(self.config["data_dir"]) / "discovery") + try: + result = await asyncio.to_thread(manager.scan, value.host, value.port) + await json_response(send, 200, result) + finally: + await asyncio.to_thread(manager.close) + return + if scope["method"] == "GET" and path == "/internal/v1/health": + await asyncio.to_thread(self.store.get, "engine", "readiness") + await json_response(send, 200, {"status": "ok"}) + return + op_match = re.fullmatch(r"/internal/v1/operations/([A-Za-z0-9_-]{8,80})", path) + if scope["method"] == "GET" and op_match: + operation = await self._operation(op_match[1], delegated) + await json_response(send, 200, self._public_operation(operation)) + return + match = re.fullmatch(r"/internal/v1/hosts/([A-Za-z0-9][A-Za-z0-9_-]{0,63})/(.+)", path) + if match is None: + raise EngineAuthError("内部资源不存在", 404) + host_id, resource = match.groups() + self._authorize_route(scope["method"], resource, delegated) + app = await self.registry.get(host_id) + if resource.endswith("/console-ticket"): + vm_id = resource.split("/")[1] + await self._ticket(host_id, vm_id, delegated, send) + return + operation = None + create = scope["method"] == "POST" and resource == "vms" + mutation = scope["method"] == "DELETE" and resource.startswith("vms/") or ( + scope["method"] == "POST" and bool(re.fullmatch( + rf"vms/{VM_ID}/(?:actions|reinstall|rescue(?:/exit|/force-start)?)", resource))) + if create or mutation: + if not OP_ID.fullmatch(delegated.get("operation_id", "")): + raise EngineAuthError("虚拟机操作缺少持久幂等编号", 403) + if create and not delegated.get("can_provision"): + raise EngineAuthError("虚拟机只能通过已确认套餐订单开通", 403) + operation, fresh = await self._reserve_operation(host_id, delegated, body, + resource=resource, method=scope["method"], target=raw_target(scope)) + if operation.get("prevalidation_failed"): + await json_response(send, 422, self._public_operation(operation)) + return + if not fresh: + if operation["status"] == "succeeded": + await json_response(send, 201 if create else 200, + {**operation["result"], **self._public_operation(operation)}) + else: + await json_response(send, 202, self._public_operation(operation)) + return + if create: + delegated["vm_uuid"] = operation["vm_uuid"] + self.active_operations.add(operation["operation_id"]) + child_scope = {**scope, "path": "/api/v1/" + resource, + "raw_path": ("/api/v1/" + resource).encode(), "root_path": ""} + if operation is None: + # Register before saving so all persisted hosts are restored for + # unattended sampling after restart, even if the HTTP caller dies. + if resource == "host" and scope["method"] == "PUT": + await asyncio.to_thread(self.store.set, "engine_host", host_id, json.dumps({"host_id": host_id})) + await app(child_scope, receive, send) + return + messages = [] + async def capture(message): + messages.append(message) + try: + await app(child_scope, receive, capture) + status = next(item["status"] for item in messages if item["type"] == "http.response.start") + payload = json.loads(b"".join(item.get("body", b"") for item in messages + if item["type"] == "http.response.body")) + operation["status"] = ("pending" if status == 202 and payload.get("job_id") else "succeeded") if 200 <= status < 300 else ( + "failed" if not create and status < 500 else "uncertain") + if operation["status"] == "succeeded": + operation["result"] = payload + elif operation["status"] == "pending": + operation["result"] = payload + operation["job_id"] = payload["job_id"] + else: + operation["error"] = payload.get("detail") or payload.get("error") or "虚拟机开通失败" + if create: + await self._check_absent(operation) + operation["finished_at"] = int(time.time()) + await asyncio.to_thread(self.store.set, "operation", operation["operation_id"], json.dumps(operation)) + if operation["status"] in {"succeeded", "pending"}: + await json_response(send, status, {**payload, **self._public_operation(operation)}) + else: + await json_response(send, status, {**payload, "operation_id": operation["operation_id"], + "status": operation["status"], "safe_to_refund": operation["safe_to_refund"]}) + except BaseException: + operation["status"] = "uncertain" + operation["error"] = "开通结果不确定,请查询操作状态,不要重复创建" + with suppress(Exception): + await asyncio.to_thread(self.store.set, "operation", operation["operation_id"], json.dumps(operation)) + raise + finally: + self.active_operations.discard(operation["operation_id"]) + + async def _reserve_operation(self, host_id, delegated, body, *, resource="vms", method="POST", target=""): + op_id = delegated["operation_id"] + # Even rejected signed provisioning requests have a durable outcome. + # A worker that loses this HTTP response can release its frozen balance + # only by querying this same operation, without replaying the request. + from .app import CreateCloudBody, CreateISOBody + from pydantic import ValidationError + create = resource == "vms" + value = {} + error = None + try: + value = json.loads(body) if body else {} + if not isinstance(value, dict): + raise ValueError("body must be an object") + if create: + (CreateCloudBody if value.get("source") == "cloud" else CreateISOBody).model_validate(value) + if value.get("guest_ssh_key_id") is not None or value.get("ssh_key_id") is not None: + error = "公钥必须由 PHP 校验用户归属后传递,不能使用旧公钥 ID" + except (ValueError, AttributeError, TypeError, ValidationError): + value = {} + error = "虚拟机参数校验失败" + record = {"operation_id": op_id, "host_id": host_id, "user_id": delegated["user_id"], + "request_hash": hmac.new(self.secret, method.encode() + b"\n" + target.encode() + b"\n" + (body or b""), hashlib.sha256).hexdigest(), + "vm_uuid": str(uuid.uuid4()) if create else str(uuid.UUID(resource.split("/")[1])), + "vm_name": value.get("name"), "kind": "create" if create else "mutation", + "resource": resource, "method": method, "status": "running", "result": None, + "safe_to_refund": False, "created_at": int(time.time())} + if error: + # No service, task, VM or volume mutation has been invoked. + record.update(status="failed", prevalidation_failed=True, + error=error, safe_to_refund=create, finished_at=int(time.time())) + fresh = await asyncio.to_thread(self.store.insert, "operation", op_id, json.dumps(record)) + if fresh: + return record, True + previous = await self._operation(op_id, delegated, reconcile=False) + if previous["host_id"] != host_id or previous["user_id"] != delegated["user_id"] or previous["request_hash"] != record["request_hash"]: + raise EngineAuthError("相同开通操作编号的请求内容不一致", 409) + return previous, False + + async def _operation(self, op_id, delegated, *, reconcile=True): + raw = await asyncio.to_thread(self.store.get, "operation", op_id) + if raw is None: + raise EngineAuthError("开通操作不存在", 404) + record = json.loads(raw) + if record["user_id"] != delegated["user_id"] and not delegated["is_admin"]: + raise EngineAuthError("开通操作不存在", 404) + # Never automatically create again. Recover a known UUID if libvirt + # committed while the response or process was lost. + if reconcile and record.get("kind") == "mutation" and record["status"] in {"running", "pending", "uncertain"}: + return await self._mutation_operation(record) + if (reconcile and record["status"] in {"running", "uncertain"} + and op_id not in self.active_operations + and (record["status"] == "uncertain" or int(time.time()) - record.get("created_at", 0) >= 120)): + await self.registry.get(record["host_id"]) + components = self.registry.components[record["host_id"]] + profile = components.manager.current() + if profile and not profile.get("key_locked"): + try: + vm = await asyncio.to_thread(self._service(profile).get_vm, record["vm_uuid"]) + if vm.get("state") != "running" or not vm.get("managed"): + return record + from .metrics import host_scope + await asyncio.to_thread(components.state.users.assign_vm, + host_scope(profile), record["vm_uuid"], record["user_id"]) + record.update(status="succeeded", result=vm, safe_to_refund=False) + await asyncio.to_thread(self.store.set, "operation", op_id, json.dumps(record)) + except Exception: + # A missing VM can be a transient connection failure or an + # operation still in progress. It is not permission to retry. + await self._check_absent(record) + await asyncio.to_thread(self.store.set, "operation", op_id, json.dumps(record)) + return record + + async def _mutation_operation(self, record): + await self.registry.get(record["host_id"]) + components = self.registry.components[record["host_id"]] + kind = "reinstall_job" if record["resource"].endswith("/reinstall") else "rescue_job" if "/rescue" in record["resource"] else None + if kind is None: + # A reset/shutdown/delete cannot be safely replayed merely because + # its response disappeared. Keep its uncertainty explicit. + return record + scoped = components.store + job = None + job_id = record.get("job_id") + if job_id: + raw = await asyncio.to_thread(scoped.get, kind, job_id) + job = json.loads(raw) if raw else None + else: + rows = await asyncio.to_thread(scoped.list, kind) + for candidate_id, raw in rows.items(): + candidate = json.loads(raw) + if candidate.get("operation_id") == record["operation_id"]: + job_id, job = candidate_id, candidate + break + if job is None: + return record + if job.get("owner") != f"php:{record['user_id']}" or job.get("vm_id") != record["vm_uuid"]: + return record + record["job_id"] = job_id + record["result"] = {key: value for key, value in job.items() if key not in {"scope", "owner", "operation_id"}} + record["result"]["job_id"] = job_id + status = job.get("status") + record["status"] = "succeeded" if status in {"completed", "succeeded"} else "running" if status in {"queued", "running"} else "failed" + if "面板重启" in job.get("phase", "") or "面板在任务执行期间重启" in job.get("error", ""): + record["status"] = "uncertain" + if job.get("error"): + record["error"] = job["error"] + await asyncio.to_thread(self.store.set, "operation", record["operation_id"], json.dumps(record)) + return record + + async def _check_absent(self, operation): + operation["safe_to_refund"] = False + components = self.registry.components.get(operation["host_id"]) + profile = components.manager.current() if components else None + if profile and not profile.get("key_locked"): + try: + absent = await asyncio.to_thread(self._service(profile).provisioning_absent, + operation["vm_uuid"], operation["vm_name"]) + if absent: + await asyncio.to_thread(self._cleanup_absent_records, components, + profile, operation["vm_uuid"]) + operation.update(status="failed", safe_to_refund=True) + except Exception: + pass + + @staticmethod + def _cleanup_absent_records(components, profile, vm_id): + from .metrics import host_scope + scope = host_scope(profile) + components.state.users.delete_vm_owner(scope, vm_id) + components.store.delete("vm_credential", f"{scope}.{vm_id}") + prefix = scope + "." + for key, raw in components.store.list("ip_claim").items(): + if key.startswith(prefix) and json.loads(raw).get("vm_uuid") == vm_id: + components.store.delete("ip_claim", key) + + @staticmethod + def _public_operation(record): + return {key: record[key] for key in ("operation_id", "status", "result", "error", "safe_to_refund", "created_at", "finished_at") + if key in record} + + @staticmethod + def _service(profile): + from .libvirt_service import VMService + return VMService(profile["libvirt_uri"], profile["storage_pool"], profile["iso_pool"], + profile["default_network"], rescue_iso_pool=profile.get("rescue_iso_pool", "")) + + async def _ticket(self, host_id, vm_id, delegated, send): + if not delegated.get("session_id"): + raise EngineAuthError("控制台需要有效的网站会话", 403) + components = self.registry.components[host_id] + profile = components.manager.current() + if profile is None or profile.get("key_locked"): + raise EngineAuthError("宿主机尚未就绪", 409) + from .metrics import host_scope + if not delegated["is_admin"] and not components.state.users.owns_vm(host_scope(profile), vm_id, delegated["user_id"]): + raise EngineAuthError("虚拟机不存在", 404) + await asyncio.to_thread(self._service(profile).console_port, vm_id) + if not await self._session_active(delegated, host_id, vm_id): + raise EngineAuthError("网站会话已失效", 403) + ticket = secrets.token_urlsafe(32) + key = hashlib.sha256(ticket.encode("ascii")).hexdigest() + record = {"host_id": host_id, "vm_id": vm_id, "actor": delegated, "expires_at": int(time.time()) + 60} + await asyncio.to_thread(self.store.insert, "console_ticket", key, json.dumps(record)) + await json_response(send, 200, {"ticket": ticket, "expires_in": 60, "websocket_path": "/engine-console"}) + + async def _session_active(self, delegated, host_id, vm_id): + if self.introspection is not None: + return await self.introspection(delegated, host_id, vm_id) + return await asyncio.to_thread(self._introspect, delegated, host_id, vm_id) + + def _introspect(self, delegated, host_id, vm_id): + url = self.config.get("php_introspection_url", "") + parsed = urlsplit(url) + if (parsed.scheme not in {"http", "https"} or parsed.hostname not in {"127.0.0.1", "::1", "localhost"} + or parsed.username or parsed.password or parsed.fragment): + return False + body = json.dumps({"session_id": delegated["session_id"], "user_id": delegated["user_id"], + "host_id": host_id, "vm_uuid": vm_id}, separators=(",", ":")).encode() + secret = decode_secret(self.config.get("introspection_secret", self.config["service_secret"])) + headers = signed_headers(secret, "POST", parsed.path + ("?" + parsed.query if parsed.query else ""), body, delegated) + headers["Content-Type"] = "application/json" + if self.config.get("php_introspection_host"): + headers["Host"] = self.config["php_introspection_host"] + try: + opener = build_opener(ProxyHandler({}), NoRedirects()) + with opener.open(URLRequest(url, body, headers, method="POST"), timeout=5) as response: + raw = response.read(8193) + return response.status == 200 and len(raw) <= 8192 and json.loads(raw).get("active") is True + except Exception: + return False + + async def _console(self, scope, receive, send): + from starlette.websockets import WebSocket + socket = WebSocket(scope, receive=receive, send=send) + if scope["path"] != "/engine-console" or scope.get("scheme") != "wss": + await socket.close(code=4403) + return + from .app import _origin_matches_host + if not _origin_matches_host(socket.headers.get("origin"), socket.headers.get("host")): + await socket.close(code=4403) + return + protocols = [value for value in scope.get("subprotocols", []) if value.startswith("cloud-ticket.")] + if len(protocols) != 1 or not re.fullmatch(r"cloud-ticket\.[A-Za-z0-9_-]{43}", protocols[0]): + await socket.close(code=4401) + return + key = hashlib.sha256(protocols[0][13:].encode("ascii")).hexdigest() + raw = await asyncio.to_thread(self.store.get, "console_ticket", key) + if raw is None: + await socket.close(code=4401) + return + record = json.loads(raw) + if record["expires_at"] < int(time.time()) or not await asyncio.to_thread(self.store.insert, "ticket_used", key, "1"): + await socket.close(code=4401) + return + await asyncio.to_thread(self.store.delete, "console_ticket", key) + delegated, host_id, vm_id = record["actor"], record["host_id"], record["vm_id"] + if not await self._session_active(delegated, host_id, vm_id): + await socket.close(code=4403) + return + token = TRUSTED_ACTOR.set(delegated) + relay = watcher = None + try: + await self.registry.get(host_id) + components = self.registry.components[host_id] + profile = components.manager.current() + from .metrics import host_scope + from .console import relay_console + if profile is None or profile.get("key_locked"): + await socket.close(code=4409) + return + if not delegated["is_admin"] and not components.state.users.owns_vm(host_scope(profile), vm_id, delegated["user_id"]): + await socket.close(code=4403) + return + port = await asyncio.to_thread(self._service(profile).console_port, vm_id) + await socket.accept(subprotocol=protocols[0]) + async def watch(): + while True: + await asyncio.sleep(self.console_check_interval) + if not await self._session_active(delegated, host_id, vm_id): + return + current = components.manager.current() + if current is None or current.get("key_locked"): + return + if not delegated["is_admin"] and not components.state.users.owns_vm(host_scope(current), vm_id, delegated["user_id"]): + return + relay = asyncio.create_task(relay_console(socket, port=port, + ssh_target=profile["ssh_target"], ssh_binary="ssh", + known_hosts_file=profile["ssh_known_hosts_file"], ssh_config_file=profile["ssh_config_file"])) + watcher = asyncio.create_task(watch()) + await asyncio.wait({relay, watcher}, return_when=asyncio.FIRST_COMPLETED) + except Exception: + LOG.warning("Engine console closed after transport/authorization failure") + finally: + for task in (relay, watcher): + if task is not None: + task.cancel() + await asyncio.gather(*(task for task in (relay, watcher) if task is not None), return_exceptions=True) + with suppress(Exception): + await socket.close(code=4403) + TRUSTED_ACTOR.reset(token) + + async def _lifespan(self, receive, send): + while True: + message = await receive() + if message["type"] == "lifespan.startup": + try: + await self.registry.start() + await send({"type": "lifespan.startup.complete"}) + except Exception: + LOG.exception("Engine startup failed") + await send({"type": "lifespan.startup.failed", "message": "引擎初始化失败"}) + return + elif message["type"] == "lifespan.shutdown": + await self.registry.close() + await send({"type": "lifespan.shutdown.complete"}) + return + + +def create_engine(): + default = Path(__file__).resolve().parents[2] / "runtime" / "engine.json" + config = private_config(Path(os.environ.get("CLOUD_ENGINE_CONFIG", str(default)))) + secret = decode_secret(config["service_secret"]) + del secret + key = master_key(Path(config["master_key_file"])) + store = MainStore(config["main_database"], key) + logs = LogStore(config["log_database"], key) + return EngineApplication(config, store, logs) diff --git a/engine/virsh_panel/libvirt_service.py b/engine/virsh_panel/libvirt_service.py new file mode 100644 index 00000000..3fd974b9 --- /dev/null +++ b/engine/virsh_panel/libvirt_service.py @@ -0,0 +1,1955 @@ +"""Small, synchronous libvirt service for one remote QEMU host. + +The URI normally has the form ``qemu+ssh://user@host/system``. The web +process must already have a non-interactive, trusted way to authenticate to +that host; libvirt-python does not turn an interactive SSH prompt into an API. +""" + +from __future__ import annotations + +import hashlib +import logging +import posixpath +import re +import secrets +import threading +import time +import uuid as uuidlib +import xml.etree.ElementTree as ET +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Callable, Iterator + +import libvirt + +from virsh_panel.cloud_init import build_seed_iso, read_seed_network, validate_cloud_network +from virsh_panel.metrics import RawVMStats + + +LOG = logging.getLogger(__name__) +GIB = 1024**3 +PANEL_NS = "urn:virsh-panel:1" +NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z") +BRIDGE_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z") +TEMPLATE_VOLUME_RE = re.compile(r"panel-template-alma(?:9|10)-[0-9a-f]{8}-[0-9a-f]{16}\.qcow2\Z") +RESCUE_VOLUME_RE = re.compile(r"panel-rescue-[0-9a-f]{32}\.iso\Z") +_CREATE_LOCK = threading.RLock() +REINSTALL_SHUTDOWN_TIMEOUT = 120 +REINSTALL_SHUTDOWN_POLL_INTERVAL = 1 +MIN_RESCUE_ISO_BYTES = 1024 * 1024 +MAX_RESCUE_ISO_BYTES = 8 * GIB +STATES = { + 0: "nostate", + 1: "running", + 2: "blocked", + 3: "paused", + 4: "shutdown", + 5: "shutoff", + 6: "crashed", + 7: "pmsuspended", +} + + +class VMError(Exception): + """An error safe to report to the authenticated panel user.""" + + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + self.status_code = status + + +class VMService: + """Operate on one host through libvirt's native API, never a shell.""" + + def __init__(self, uri: str, storage_pool: str, iso_pool: str, network: str, + rescue_iso_pool: str = "") -> None: + if not all(isinstance(value, str) and value for value in + (uri, storage_pool, iso_pool, network)): + raise ValueError("libvirt URI, storage pools, and network are required") + if not isinstance(rescue_iso_pool, str): + raise ValueError("rescue ISO pool must be a string") + self.uri = uri + self.storage_pool = storage_pool + self.iso_pool = iso_pool + self.rescue_iso_pool = rescue_iso_pool + self.network = network + self.bridge_name = None + if network.startswith("bridge:"): + self.bridge_name = network.removeprefix("bridge:") + if not BRIDGE_NAME_RE.fullmatch(self.bridge_name): + raise ValueError("bridge network must name a host interface of at most 15 characters") + + @contextmanager + def _connect(self) -> Iterator[Any]: + try: + conn = libvirt.open(self.uri) + if conn is None: + raise VMError("无法连接虚拟化宿主机", 502) + except libvirt.libvirtError as exc: + LOG.warning("libvirt connection failed: %s", exc) + raise VMError("无法连接虚拟化宿主机", 502) from exc + try: + yield conn + except libvirt.libvirtError as exc: + LOG.warning("libvirt operation failed: %s", exc) + raise VMError("宿主机操作失败,请查看面板服务日志", 502) from exc + finally: + try: + conn.close() + except libvirt.libvirtError: + LOG.exception("Could not close libvirt connection") + + @staticmethod + def _uuid(value: str) -> str: + try: + return str(uuidlib.UUID(value)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效", 400) from exc + + def _domain(self, conn: Any, value: str) -> Any: + vm_uuid = self._uuid(value) + for domain in conn.listAllDomains(0): + if domain.UUIDString() == vm_uuid: + return domain + raise VMError("虚拟机不存在", 404) + + @staticmethod + def _pool_path(reference: str) -> str | None: + if not reference.startswith("/"): + return None + if ("\x00" in reference or reference.startswith("//") + or any(part in (".", "..") for part in reference.split("/"))): + raise VMError("存储池目录必须是不含 . 或 .. 的绝对路径") + path = posixpath.normpath(reference) + if path == "/": + raise VMError("不能将宿主机根目录用作存储池") + return path + + @staticmethod + def _file_pool_path(pool: Any) -> str | None: + """Compare paths for file-backed pools, including fs/netfs aliases.""" + try: + root = ET.fromstring(pool.XMLDesc(0)) + except ET.ParseError as exc: + raise VMError("宿主机返回的存储池配置 XML 无效", 502) from exc + if root.get("type") not in {"dir", "fs", "netfs"}: + return None + path = root.findtext("./target/path") + return posixpath.normpath(path) if path and path.startswith("/") else None + + @staticmethod + def _directory_pool_path(pool: Any) -> str | None: + try: + root = ET.fromstring(pool.XMLDesc(0)) + except ET.ParseError as exc: + raise VMError("宿主机返回的存储池配置 XML 无效", 502) from exc + if root.get("type") != "dir": + return None + path = root.findtext("./target/path") + return posixpath.normpath(path) if path and path.startswith("/") else None + + def _lookup_pool(self, conn: Any, reference: str) -> Any | None: + path = self._pool_path(reference) + if path is None: + try: + return conn.storagePoolLookupByName(reference) + except libvirt.libvirtError as exc: + LOG.info("Storage pool %s is not defined: %s", reference, exc) + return None + matches = [pool for pool in conn.listAllStoragePools(0) + if self._file_pool_path(pool) == path] + if len(matches) > 1: + raise VMError(f"目录 {path} 对应多个 libvirt 存储池,请在宿主机处理重复配置", 409) + return matches[0] if matches else None + + def _active_pool(self, conn: Any, reference: str) -> Any: + pool = self._lookup_pool(conn, reference) + if pool is None: + if self._pool_path(reference) is not None: + raise VMError(f"目录 {reference} 尚未配置为 libvirt 存储池,请先保存宿主机设置", 409) + raise VMError(f"存储池 {reference} 不存在", 404) + if not pool.isActive(): + raise VMError(f"存储池 {pool.name()} 未启动", 409) + return pool + + @classmethod + def _same_pool_location(cls, first: Any, second: Any) -> bool: + if first.name() == second.name(): + return True + first_path = cls._file_pool_path(first) + second_path = cls._file_pool_path(second) + return first_path is not None and first_path == second_path + + def _active_rescue_pool(self, conn: Any) -> Any: + if not self.rescue_iso_pool: + raise VMError("请先在宿主机设置中配置救援 ISO 目录", 409) + pool = self._active_pool(conn, self.rescue_iso_pool) + normal_pool = self._lookup_pool(conn, self.iso_pool) + if normal_pool is not None and self._same_pool_location(pool, normal_pool): + raise VMError("救援 ISO 目录不能与安装 ISO 目录相同", 409) + return pool + + @classmethod + def _refresh_directory_pool(cls, pool: Any) -> None: + # ISO files and disk images may be placed into these directories + # outside libvirt. Refresh before looking up names or checking for + # collisions so libvirt's cached volume list is not stale. + if cls._directory_pool_path(pool) is not None: + pool.refresh(0) + + @staticmethod + def _directory_pool_xml(name: str, path: str) -> str: + root = ET.Element("pool", type="dir") + ET.SubElement(root, "name").text = name + target = ET.SubElement(root, "target") + ET.SubElement(target, "path").text = path + return ET.tostring(root, encoding="unicode") + + @staticmethod + def _rollback_new_pool(pool: Any) -> bool: + """Remove only a definition created by this ensure call, not its files.""" + restored = True + try: + if pool.isActive(): + pool.destroy() + except libvirt.libvirtError: + LOG.exception("Could not stop newly defined pool %s during rollback", pool.name()) + restored = False + try: + pool.undefine() + except libvirt.libvirtError: + LOG.exception("Could not undefine newly defined pool %s during rollback", pool.name()) + restored = False + return restored + + def _ensure_pool(self, conn: Any, reference: str, created_pools: list[Any]) -> Any: + path = self._pool_path(reference) + pool = self._lookup_pool(conn, reference) + if pool is None: + if path is None: + raise VMError(f"存储池 {reference} 不存在;请填写已存在的池名或宿主机绝对目录", 404) + # A path is a host directory, never an XML pool name. A stable + # name keeps domain XML valid across panel and libvirt restarts. + name = "panel-dir-" + hashlib.sha256(path.encode("utf-8")).hexdigest()[:48] + try: + collision = conn.storagePoolLookupByName(name) + except libvirt.libvirtError: + collision = None + if collision is not None: + raise VMError(f"自动生成的存储池名称 {name} 已被其他目录占用", 409) + try: + pool = conn.storagePoolDefineXML(self._directory_pool_xml(name, path), 0) + except libvirt.libvirtError as exc: + LOG.warning("Could not define directory pool %s for %s: %s", name, path, exc) + raise VMError(f"无法为目录 {path} 定义 libvirt 存储池", 502) from exc + if pool is None: + raise VMError(f"无法为目录 {path} 定义 libvirt 存储池", 502) + created_pools.append(pool) + if not pool.isPersistent(): + raise VMError(f"存储池 {pool.name()} 是临时池,无法在宿主机重启后自动启动", 409) + try: + if not pool.isActive(): + pool.create(0) + except libvirt.libvirtError as exc: + LOG.warning("Could not start directory pool %s: %s", pool.name(), exc) + if path is not None: + raise VMError(f"目录 {path} 不存在或 libvirt 无权访问;请检查宿主机目录和 SELinux 权限", 409) from exc + raise VMError(f"存储池 {reference} 无法启动", 409) from exc + if not pool.autostart(): + try: + pool.setAutostart(1) + except libvirt.libvirtError as exc: + LOG.warning("Could not enable autostart for pool %s: %s", pool.name(), exc) + raise VMError(f"无法设置存储池 {pool.name()} 随宿主机启动", 502) from exc + return pool + + def ensure_storage_pools(self) -> dict[str, str]: + """Explicitly define/start configured directory pools; never build paths.""" + with self._connect() as conn: + created_pools: list[Any] = [] + try: + disk_pool = self._ensure_pool(conn, self.storage_pool, created_pools) + iso_pool = self._ensure_pool(conn, self.iso_pool, created_pools) + pools = {"storage_pool": disk_pool.name(), "iso_pool": iso_pool.name()} + if self.rescue_iso_pool: + rescue_pool = self._ensure_pool( + conn, self.rescue_iso_pool, created_pools) + if self._same_pool_location(iso_pool, rescue_pool): + raise VMError("救援 ISO 目录不能与安装 ISO 目录相同", 409) + pools["rescue_iso_pool"] = rescue_pool.name() + return pools + except Exception as exc: + rolled_back = True + for pool in reversed(created_pools): + if not self._rollback_new_pool(pool): + rolled_back = False + if not rolled_back: + raise VMError("存储池配置失败且新建存储池回滚失败;请检查宿主机", 502) from exc + raise + + @staticmethod + def _vm_xml(domain: Any) -> ET.Element: + try: + return ET.fromstring(domain.XMLDesc(0)) + except ET.ParseError as exc: + raise VMError("宿主机返回的虚拟机配置 XML 无效", 502) from exc + + @staticmethod + def _disk_rows(root: ET.Element) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + for disk in root.findall("./devices/disk"): + if disk.get("device") != "disk": + continue + source = disk.find("source") + target = disk.find("target") + driver = disk.find("driver") + source_name = "" + if source is not None: + source_name = (source.get("volume") or source.get("file") + or source.get("dev") or "") + rows.append({ + "device": disk.get("device", "disk"), + "source": source_name, + "target": target.get("dev", "") if target is not None else "", + "format": driver.get("type", "") if driver is not None else "", + }) + return rows + + @staticmethod + def _vnc_port(root: ET.Element) -> int | None: + for graphics in root.findall("./devices/graphics"): + if graphics.get("type") == "vnc": + # The relay always connects to the hypervisor's IPv4 loopback. + # Do not advertise a console that listens on another address. + listeners = [graphics.get("listen")] + listeners.extend(node.get("address") for node in graphics.findall("listen")) + if not listeners or any(address not in (None, "127.0.0.1") for address in listeners): + return None + if all(address is None for address in listeners): + return None + try: + port = int(graphics.get("port", "-1")) + except ValueError: + return None + return port if 1 <= port <= 65535 else None + return None + + def _vm_dict(self, domain: Any) -> dict[str, Any]: + info = domain.info() + root = self._vm_xml(domain) + disks = self._disk_rows(root) + for disk in disks: + identifier = disk["target"] or disk["source"] + if not identifier: + continue + try: + capacity, _allocation, _physical = domain.blockInfo(identifier, 0) + except libvirt.libvirtError: + # The domain remains manageable when an external storage + # backend cannot report its capacity (for example, RBD). + continue + if isinstance(capacity, int) and capacity > 0: + disk["capacity_gib"] = round(capacity / GIB, 2) + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + rescue = root.find(f"./metadata/{{{PANEL_NS}}}rescue") + rescue_staged = False + inactive_rescue = None + if domain.isPersistent(): + try: + inactive_root = ET.fromstring( + domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + except ET.ParseError as exc: + raise VMError("宿主机返回的虚拟机持久配置 XML 无效", 502) from exc + inactive_rescue = inactive_root.find(f"./metadata/{{{PANEL_NS}}}rescue") + # Defining the next boot does not replace the live QEMU process. + # A stopped VM with a rescue definition is staged until first boot. + rescue_staged = inactive_rescue is not None and ( + not domain.isActive() or rescue is None) + os_source = managed.get("os-source") if managed is not None else None + if os_source not in {"cloud_template", "iso"}: + os_source = "unknown" + try: + autostart = bool(domain.autostart()) + except libvirt.libvirtError: + autostart = False + return { + "uuid": domain.UUIDString(), + "name": domain.name(), + "state": STATES.get(info[0], "unknown"), + "vcpu": info[3], + "memory_mib": info[1] // 1024, + "disks": disks, + "autostart": autostart, + "managed": managed is not None, + "public_ip_cidr": managed.get("public-ip-cidr") if managed is not None else None, + "created_at": managed.get("created-at") if managed is not None else None, + "credential_generation": managed.get("seed-volume") if os_source == "cloud_template" else None, + "os_name": managed.get("os-name") if os_source == "cloud_template" else None, + "os_source": os_source, + "install_iso": managed.get("install-iso") if os_source == "iso" else None, + "rescue_mode": rescue is not None, + "rescue_staged": rescue_staged, + "rescue_volume_name": ( + rescue.get("volume") if rescue is not None else + inactive_rescue.get("volume") if inactive_rescue is not None else None), + "console_port": self._vnc_port(root), + } + + @staticmethod + def _enable_vm_autostart(domain: Any) -> None: + """Require host-boot autostart on a new persistent VM definition.""" + try: + domain.setAutostart(1) + except libvirt.libvirtError as exc: + LOG.warning("Could not enable VM autostart: %s", exc) + raise VMError("无法设置新虚拟机随宿主机开机自启", 502) from exc + + def list_vms(self) -> list[dict[str, Any]]: + with self._connect() as conn: + return sorted( + (self._vm_dict(domain) for domain in conn.listAllDomains(0)), + key=lambda row: row["name"].casefold(), + ) + + def provisioning_absent(self, vm_uuid: str, name: str) -> bool: + """Only certify refund safety after a fresh host/volume inventory. + + Any connection failure, external disk collision or partial rollback is + deliberately not evidence that a financial refund is safe. + """ + vm_uuid = self._uuid(vm_uuid) + if not isinstance(name, str) or not NAME_RE.fullmatch(name): + return False + with self._connect() as conn: + if any(domain.UUIDString() == vm_uuid for domain in conn.listAllDomains(0)): + return False + pool = self._active_pool(conn, self.storage_pool) + self._refresh_directory_pool(pool) + volumes = set(pool.listVolumes()) + return not {f"{name}.qcow2", f"panel-seed-{vm_uuid}.iso"}.intersection(volumes) + + def get_vm(self, uuid: str) -> dict[str, Any]: + with self._connect() as conn: + return self._vm_dict(self._domain(conn, uuid)) + + def metric_counters(self) -> list[RawVMStats]: + """Fetch running-domain counters in one libvirt API round trip. + + getAllDomainStats(stats, flags) returns ``(domain, dict)`` pairs in + libvirt-python. Network rx/tx fields are from the guest's viewpoint. + Missing per-device values are preserved as missing by the sampler. + """ + groups = (libvirt.VIR_DOMAIN_STATS_CPU_TOTAL | libvirt.VIR_DOMAIN_STATS_BALLOON + | libvirt.VIR_DOMAIN_STATS_BLOCK | libvirt.VIR_DOMAIN_STATS_INTERFACE) + running = libvirt.VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING + with self._connect() as conn: + rows: list[RawVMStats] = [] + for domain, values in conn.getAllDomainStats(groups, running): + # A guest can stop or be undefined after bulk stats are read. + # Do not lose all other guests' samples for that transient race. + try: + info = domain.info() + generation = domain.ID() + vm_id = domain.UUIDString() + except libvirt.libvirtError: + continue + if info[0] != 1 or generation < 0: + continue + rows.append(RawVMStats( + vm_id=vm_id, generation=generation, + vcpus=info[3], values=values, + )) + return rows + + def resources(self) -> dict[str, Any]: + with self._connect() as conn: + disk_pool = self._active_pool(conn, self.storage_pool) + iso_pool = self._active_pool(conn, self.iso_pool) + self._refresh_directory_pool(iso_pool) + if self.bridge_name is None: + network = conn.networkLookupByName(self.network) + active_networks = [self.network] if network.isActive() else [] + else: + # Linux bridges live outside libvirt's virtual-network API. + # Advertise the configured selector and let domain startup + # report a missing/inactive bridge on the actual host. + active_networks = [self.network] + isos = sorted(name for name in iso_pool.listVolumes() + if name.lower().endswith(".iso") + and not RESCUE_VOLUME_RE.fullmatch(name)) + pool_info = disk_pool.info() + return { + "storage_pool": self.storage_pool, + "networks": active_networks, + "isos": isos, + "storage_available_gib": pool_info[3] // GIB, + } + + def _validate_common_create(self, spec: dict[str, Any]) -> dict[str, Any]: + if not isinstance(spec, dict): + raise VMError("虚拟机配置无效") + name = spec.get("name") + if not isinstance(name, str) or not NAME_RE.fullmatch(name): + raise VMError("名称只能包含字母、数字、点、下划线或短横线,最长 63 字符") + bounds = { + "vcpu": (1, 64), + "memory_mib": (512, 262144), + "disk_gib": (1, 4096), + } + validated: dict[str, Any] = {"name": name} + for key, (minimum, maximum) in bounds.items(): + value = spec.get(key) + if isinstance(value, bool) or not isinstance(value, int) or not minimum <= value <= maximum: + raise VMError(f"{key} 必须是 {minimum} 到 {maximum} 的整数") + validated[key] = value + if spec.get("network") != self.network: + raise VMError("只能选择面板配置的虚拟网络或网桥") + bandwidth = spec.get("bandwidth_mbps") + if bandwidth is not None: + if isinstance(bandwidth, bool) or not isinstance(bandwidth, int) or not 1 <= bandwidth <= 100000: + raise VMError("带宽必须是 1 至 100000 Mbps 的整数") + validated["bandwidth_mbps"] = bandwidth + return validated + + def _validate_create(self, spec: dict[str, Any]) -> dict[str, Any]: + validated = self._validate_common_create(spec) + iso = spec.get("iso") + if not isinstance(iso, str) or not iso.lower().endswith(".iso"): + raise VMError("请选择 ISO 存储池内的安装镜像") + if RESCUE_VOLUME_RE.fullmatch(iso): + raise VMError("救援镜像不能用作虚拟机安装 ISO", 409) + validated["iso"] = iso + return validated + + @staticmethod + def _validated_os_name(value: Any) -> str | None: + if value is None: + return None + if (not isinstance(value, str) or not 1 <= len(value) <= 64 + or value != value.strip() or any(ord(char) < 32 for char in value)): + raise VMError("云镜像模板名称无效") + return value + + @staticmethod + def _volume_xml(name: str, disk_gib: int) -> str: + return VMService._volume_xml_bytes(name, disk_gib * GIB, "qcow2") + + @staticmethod + def _volume_xml_bytes(name: str, capacity: int, fmt: str) -> str: + root = ET.Element("volume") + ET.SubElement(root, "name").text = name + ET.SubElement(root, "capacity", unit="bytes").text = str(capacity) + target = ET.SubElement(root, "target") + ET.SubElement(target, "format", type=fmt) + return ET.tostring(root, encoding="unicode") + + @classmethod + def _volume_source(cls, pool: Any, volume: Any) -> tuple[str, dict[str, str]]: + """Use the actual host path for directory-backed storage volumes.""" + directory = cls._directory_pool_path(pool) + if directory is None: + return "volume", {"pool": pool.name(), "volume": volume.name()} + path = volume.path() + if (not isinstance(path, str) or not posixpath.isabs(path) + or posixpath.dirname(posixpath.normpath(path)) != directory): + raise VMError("存储卷路径不在面板配置的宿主机目录中", 502) + return "file", {"file": posixpath.normpath(path)} + + def _domain_xml(self, spec: dict[str, Any], vm_uuid: str, disk_name: str, + disk_source: tuple[str, dict[str, str]], + iso_source: tuple[str, dict[str, str]], *, + install_phase: bool) -> str: + root = ET.Element("domain", type="kvm") + ET.SubElement(root, "name").text = spec["name"] + ET.SubElement(root, "uuid").text = vm_uuid + ET.SubElement(root, "memory", unit="MiB").text = str(spec["memory_mib"]) + ET.SubElement(root, "vcpu", placement="static").text = str(spec["vcpu"]) + os_node = ET.SubElement(root, "os", firmware="efi") + # AlmaLinux 10's x86_64 OVMF descriptors target Q35 machines. An + # unspecified machine can resolve to i440fx and make firmware='efi' + # fail even when virt-install --boot uefi succeeds on the same host. + ET.SubElement(os_node, "type", arch="x86_64", machine="q35").text = "hvm" + if install_phase: + ET.SubElement(os_node, "boot", dev="cdrom") + ET.SubElement(os_node, "boot", dev="hd") + # x86 UEFI firmware requires ACPI; virt-install also enables APIC. + features = ET.SubElement(root, "features") + ET.SubElement(features, "acpi") + ET.SubElement(features, "apic") + ET.SubElement(root, "cpu", mode="host-passthrough") + if install_phase: + # The installer's first reboot shuts the transient guest off. + # The next panel Start uses the persistent, ISO-free definition. + ET.SubElement(root, "on_reboot").text = "destroy" + metadata = ET.SubElement(root, "metadata") + managed = ET.SubElement(metadata, f"{{{PANEL_NS}}}managed", version="2", + **{"disk-volume": disk_name}) + if spec.get("created_at"): + managed.set("created-at", spec["created_at"]) + if "iso" in spec: + # The installation media does not prove which OS was installed. + managed.set("os-source", "iso") + managed.set("install-iso", spec["iso"]) + devices = ET.SubElement(root, "devices") + + disk = ET.SubElement(devices, "disk", type=disk_source[0], device="disk") + ET.SubElement(disk, "driver", name="qemu", type="qcow2", + cache="none", discard="unmap") + ET.SubElement(disk, "source", **disk_source[1]) + ET.SubElement(disk, "target", dev="vda", bus="virtio") + + cdrom = ET.SubElement(devices, "disk", type=iso_source[0] if install_phase else "file", + device="cdrom") + ET.SubElement(cdrom, "driver", name="qemu", type="raw") + if install_phase: + ET.SubElement(cdrom, "source", **iso_source[1]) + ET.SubElement(cdrom, "target", dev="sda", bus="sata") + ET.SubElement(cdrom, "readonly") + + if self.bridge_name is None: + interface = ET.SubElement(devices, "interface", type="network") + ET.SubElement(interface, "source", network=self.network) + else: + interface = ET.SubElement(devices, "interface", type="bridge") + ET.SubElement(interface, "source", bridge=self.bridge_name) + ET.SubElement(interface, "model", type="virtio") + # RHEL 10 recommends one virtio-net queue per vCPU, up to 16. + ET.SubElement(interface, "driver", queues=str(min(spec["vcpu"], 16))) + if spec.get("bandwidth_mbps"): + # libvirt average/peak use KiB/s, while packages use decimal Mbps. + rate = (spec["bandwidth_mbps"] * 1_000_000 + 8191) // 8192 + bandwidth = ET.SubElement(interface, "bandwidth") + for direction in ("inbound", "outbound"): + ET.SubElement(bandwidth, direction, average=str(rate), peak=str(rate)) + graphics = ET.SubElement(devices, "graphics", type="vnc", port="-1", + autoport="yes", listen="127.0.0.1") + ET.SubElement(graphics, "listen", type="address", address="127.0.0.1") + video = ET.SubElement(devices, "video") + ET.SubElement(video, "model", type="vga") + ET.SubElement(devices, "input", type="tablet", bus="usb") + channel = ET.SubElement(devices, "channel", type="unix") + ET.SubElement(channel, "target", type="virtio", name="org.qemu.guest_agent.0") + memballoon = ET.SubElement(devices, "memballoon", model="virtio", + freePageReporting="on") + ET.SubElement(memballoon, "stats", period="10") + return ET.tostring(root, encoding="unicode") + + def _rollback_new_vm(self, conn: Any, vm_uuid: str, name: str, + pool: Any, volume: Any, disk_name: str) -> bool: + """Delete the new disk only after verifying its VM no longer exists.""" + try: + domains = [domain for domain in conn.listAllDomains(0) + if domain.UUIDString() == vm_uuid] + if len(domains) > 1 or any(domain.name() != name for domain in domains): + LOG.error("Cannot safely identify new domain %s during rollback", vm_uuid) + return False + for domain in domains: + persistent = bool(domain.isPersistent()) + if domain.isActive(): + domain.destroy() + if persistent: + self._undefine_domain(domain, remove_nvram=True) + remaining = conn.listAllDomains(0) + if any(domain.UUIDString() == vm_uuid for domain in remaining): + LOG.error("New domain %s still exists after rollback", vm_uuid) + return False + # An external actor could have attached this newly created volume + # while the install was starting. Inspect both running and saved + # definitions before deleting it; uncertainty means retain it. + volume_path = volume.path() + pool_name = pool.name() + if not isinstance(volume_path, str) or not volume_path: + LOG.error("Cannot resolve volume %s path during rollback", disk_name) + return False + for other in remaining: + flags = [0] + if other.isActive() and other.isPersistent(): + flags.append(libvirt.VIR_DOMAIN_XML_INACTIVE) + for flag in flags: + root = ET.fromstring(other.XMLDesc(flag)) + for source in self._all_disk_sources(root): + if ((source.get("pool") == pool_name + and source.get("volume") == disk_name) + or volume_path in (source.get("file"), source.get("dev"))): + LOG.error("Another domain references volume %s; retaining it", disk_name) + return False + except Exception: + LOG.exception("Could not roll back domain %s; retaining disk %s", vm_uuid, disk_name) + return False + try: + volume.delete(0) + except Exception: + LOG.exception("Could not roll back volume %s", disk_name) + return False + return True + + @staticmethod + def _upload_volume(conn: Any, volume: Any, chunks: Iterator[bytes], size: int) -> None: + """Upload a local image through libvirt's authenticated SSH transport.""" + stream = conn.newStream(0) + try: + volume.upload(stream, 0, size, 0) + uploaded = 0 + for chunk in chunks: + if not isinstance(chunk, bytes): + raise VMError("镜像上传数据无效", 502) + pending = chunk + while pending: + sent = stream.send(pending) + if not isinstance(sent, int) or sent <= 0: + raise VMError("宿主机镜像上传中断", 502) + uploaded += sent + pending = pending[sent:] + if uploaded != size: + raise VMError("宿主机镜像上传长度不匹配", 502) + stream.finish() + except Exception: + try: + stream.abort() + except Exception: + LOG.exception("Could not abort failed libvirt volume upload") + raise + + @staticmethod + def _download_seed_volume(conn: Any, volume: Any) -> bytes: + """Read only a small CIDATA image through libvirt's SSH transport.""" + size = int(volume.info()[1]) + if not 0 < size <= 1024 * 1024: + raise VMError("原 cloud-init 配置盘大小无效,无法自动恢复网络", 409) + stream = conn.newStream(0) + try: + volume.download(stream, 0, size, 0) + chunks = [] + remaining = size + while remaining: + chunk = stream.recv(min(65536, remaining)) + if not isinstance(chunk, bytes) or not chunk: + raise VMError("原 cloud-init 配置盘读取不完整", 502) + chunks.append(chunk) + remaining -= len(chunk) + stream.finish() + return b"".join(chunks) + except Exception: + try: + stream.abort() + except Exception: + LOG.exception("Could not abort failed libvirt volume download") + raise + + def import_template(self, image_path: Path, volume_name: str, + virtual_size: int) -> dict[str, Any]: + """Place a verified qcow2 image in the configured host disk pool.""" + if not TEMPLATE_VOLUME_RE.fullmatch(volume_name): + raise VMError("模板卷名称无效") + if not isinstance(virtual_size, int) or not GIB <= virtual_size <= 4096 * GIB: + raise VMError("模板虚拟容量无效") + image_path = Path(image_path) + image_size = image_path.stat().st_size + with self._connect() as conn: + pool = self._active_pool(conn, self.storage_pool) + self._refresh_directory_pool(pool) + if volume_name in pool.listVolumes(): + raise VMError("同名模板镜像已存在,不会覆盖", 409) + if image_size > pool.info()[3]: + raise VMError("宿主机存储池空间不足,无法导入模板", 409) + volume = pool.createXML(self._volume_xml_bytes( + volume_name, virtual_size, "qcow2"), 0) + if volume is None: + raise VMError("宿主机未能创建模板卷", 502) + try: + def read_chunks() -> Iterator[bytes]: + with image_path.open("rb") as image: + while chunk := image.read(1024 * 1024): + yield chunk + + self._upload_volume(conn, volume, read_chunks(), image_size) + self._refresh_directory_pool(pool) + uploaded = pool.storageVolLookupByName(volume_name) + uploaded_xml = ET.fromstring(uploaded.XMLDesc(0)) + uploaded_format = uploaded_xml.find("./target/format") + if (uploaded_format is None or uploaded_format.get("type") != "qcow2" + or int(uploaded.info()[1]) != virtual_size): + raise VMError("宿主机模板卷的格式或容量与原镜像不一致", 502) + return {"volume_name": volume_name, "virtual_size": virtual_size, + "image_bytes": image_size} + except Exception as exc: + try: + volume.delete(0) + except Exception: + LOG.exception("Template upload failed and volume %s remains", volume_name) + raise VMError( + f"模板导入失败且宿主机卷 {volume_name} 未能清理,请人工检查", 502, + ) from exc + if isinstance(exc, VMError): + raise + LOG.warning("Template upload failed for %s: %s", volume_name, exc) + raise VMError("模板镜像上传到宿主机失败", 502) from exc + + @staticmethod + def _check_rescue_volume_name(volume_name: str) -> None: + if not isinstance(volume_name, str) or not RESCUE_VOLUME_RE.fullmatch(volume_name): + raise VMError("救援镜像卷名称无效") + + def _lookup_rescue_volume(self, conn: Any, volume_name: str) -> tuple[Any, Any]: + self._check_rescue_volume_name(volume_name) + pool = self._active_rescue_pool(conn) + self._refresh_directory_pool(pool) + if volume_name not in pool.listVolumes(): + raise VMError("救援镜像在宿主机上不存在,请重新上传", 404) + volume = pool.storageVolLookupByName(volume_name) + self._volume_source(pool, volume) + return pool, volume + + def _rescue_volume(self, conn: Any, volume_name: str) -> tuple[Any, Any]: + pool, volume = self._lookup_rescue_volume(conn, volume_name) + try: + root = ET.fromstring(volume.XMLDesc(0)) + fmt = root.find("./target/format") + size = int(volume.info()[1]) + except (ET.ParseError, TypeError, ValueError) as exc: + raise VMError("救援镜像卷信息无效", 502) from exc + if (fmt is None or fmt.get("type") != "raw" + or not MIN_RESCUE_ISO_BYTES <= size <= MAX_RESCUE_ISO_BYTES): + raise VMError("救援镜像必须是有效大小的 raw ISO 卷", 409) + return pool, volume + + def import_rescue_iso(self, image_path: Path, volume_name: str) -> dict[str, Any]: + """Upload one administrator-supplied ISO to the dedicated rescue pool.""" + self._check_rescue_volume_name(volume_name) + image_path = Path(image_path) + if image_path.is_symlink() or not image_path.is_file(): + raise VMError("救援镜像文件无效") + image_size = image_path.stat().st_size + if not MIN_RESCUE_ISO_BYTES <= image_size <= MAX_RESCUE_ISO_BYTES: + raise VMError("救援 ISO 大小必须在 1 MiB 至 8 GiB 之间", 422) + with image_path.open("rb") as image: + image.seek(32769) + if image.read(5) != b"CD001": + raise VMError("上传的文件不是 ISO 9660 镜像", 422) + with self._connect() as conn: + pool = self._active_rescue_pool(conn) + self._refresh_directory_pool(pool) + if volume_name in pool.listVolumes(): + raise VMError("同名救援镜像已存在,不会覆盖", 409) + if image_size > pool.info()[3]: + raise VMError("宿主机救援 ISO 存储池空间不足", 409) + volume = pool.createXML(self._volume_xml_bytes( + volume_name, image_size, "raw"), 0) + if volume is None: + raise VMError("宿主机未能创建救援镜像卷", 502) + try: + def read_chunks() -> Iterator[bytes]: + with image_path.open("rb") as image: + while chunk := image.read(1024 * 1024): + yield chunk + + self._upload_volume(conn, volume, read_chunks(), image_size) + self._rescue_volume(conn, volume_name) + return {"volume_name": volume_name, "image_bytes": image_size} + except Exception as exc: + try: + volume.delete(0) + except Exception: + LOG.exception("Rescue ISO upload failed and volume %s remains", volume_name) + raise VMError( + f"救援镜像上传失败且宿主机卷 {volume_name} 未能清理,请人工检查", 502, + ) from exc + if isinstance(exc, VMError): + raise + LOG.warning("Rescue ISO upload failed for %s: %s", volume_name, exc) + raise VMError("救援镜像上传到宿主机失败", 502) from exc + + def delete_rescue_iso(self, volume_name: str) -> dict[str, Any]: + """Delete only a panel-named rescue ISO unused by every domain.""" + with _CREATE_LOCK, self._connect() as conn: + pool, volume = self._lookup_rescue_volume(conn, volume_name) + if self._other_domain_uses_volume( + conn, "", pool.name(), volume_name, volume.path()): + raise VMError("救援镜像仍被虚拟机引用,不能删除", 409) + volume.delete(0) + return {"volume_name": volume_name, "deleted": True} + + @staticmethod + def _rescue_original_hash(original_xml: str) -> str: + if not isinstance(original_xml, str) or not original_xml: + raise VMError("原虚拟机配置备份无效", 409) + return hashlib.sha256(original_xml.encode("utf-8")).hexdigest() + + @staticmethod + def _rescue_xml_matches(first: str, second: str) -> bool: + try: + return ET.canonicalize(first) == ET.canonicalize(second) + except ET.ParseError as exc: + raise VMError("虚拟机配置 XML 无效", 502) from exc + + @staticmethod + def _rescue_vm_preflight(domain: Any) -> str: + if not domain.isPersistent(): + raise VMError("只有持久化虚拟机可以进入救援模式", 409) + if getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0): + raise VMError("虚拟机存在托管保存状态,请先处理后再救援", 409) + original_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + try: + root = ET.fromstring(original_xml) + except ET.ParseError as exc: + raise VMError("虚拟机配置 XML 无效", 502) from exc + if root.find(f"./metadata/{{{PANEL_NS}}}rescue") is not None: + raise VMError("虚拟机已处于救援模式", 409) + if root.find("./devices/disk[@device='disk']") is None: + raise VMError("虚拟机没有系统磁盘,不能进入救援模式", 409) + return original_xml + + @staticmethod + def _rescue_xml(original_xml: str, vm_uuid: str, volume_name: str, + source: tuple[str, dict[str, str]], autostart: bool) -> str: + try: + root = ET.fromstring(original_xml) + except ET.ParseError as exc: + raise VMError("原虚拟机配置备份无效", 409) from exc + if root.findtext("uuid") != vm_uuid: + raise VMError("原虚拟机配置备份与目标虚拟机不匹配", 409) + os_node = root.find("os") + devices = root.find("devices") + if os_node is None or devices is None: + raise VMError("原虚拟机配置缺少启动或设备信息", 409) + disks = [disk for disk in devices.findall("disk") + if disk.get("device") == "disk"] + if not disks: + raise VMError("虚拟机没有系统磁盘,不能进入救援模式", 409) + explicitly_booted = [disk for disk in disks + if (disk.find("boot") is not None + and disk.find("boot").get("order") == "1")] + if len(explicitly_booted) == 1: + primary = explicitly_booted[0] + else: + primary = next((disk for disk in disks + if disk.find("target") is not None + and disk.find("target").get("dev") == "vda"), None) + if primary is None and len(disks) == 1: + primary = disks[0] + if primary is None: + raise VMError("无法确定多磁盘虚拟机的系统盘,请先确认原启动顺序", 409) + # A cloud-init seed ISO often occupies the existing CD-ROM. Booting + # "cdrom" as a class could select the wrong image, so target the new + # device explicitly and keep every original device unchanged in the + # saved XML used on exit. + for boot in list(os_node.findall("boot")): + os_node.remove(boot) + for device in devices: + for boot in list(device.findall("boot")): + device.remove(boot) + ET.SubElement(primary, "boot", order="2") + used_targets = {target.get("dev") for target in devices.findall("./disk/target")} + rescue_target = next((f"sd{chr(code)}" for code in range(ord("a"), ord("z") + 1) + if f"sd{chr(code)}" not in used_targets), None) + if rescue_target is None: + raise VMError("虚拟机没有可用的 SATA 光驱目标位置", 409) + cdrom = ET.SubElement(devices, "disk", type=source[0], device="cdrom") + ET.SubElement(cdrom, "driver", name="qemu", type="raw") + ET.SubElement(cdrom, "source", **source[1]) + ET.SubElement(cdrom, "target", dev=rescue_target, bus="sata") + ET.SubElement(cdrom, "readonly") + ET.SubElement(cdrom, "boot", order="1") + metadata = root.find("metadata") + if metadata is None: + metadata = ET.SubElement(root, "metadata") + ET.SubElement(metadata, f"{{{PANEL_NS}}}rescue", + volume=volume_name, + **{"original-sha256": VMService._rescue_original_hash(original_xml), + "original-autostart": "1" if autostart else "0"}) + return ET.tostring(root, encoding="unicode") + + @staticmethod + def _restore_rescue_autostart(domain: Any, enabled: bool) -> None: + if bool(domain.autostart()) != enabled: + domain.setAutostart(int(enabled)) + + @staticmethod + def _wait_for_rescue_shutdown(domain: Any, phase: str) -> None: + if not domain.isActive(): + return + if phase == "救援启动": + next_step = ( + "救援 ISO 已写入下次冷启动配置。请先刷新虚拟机状态;如仍在运行," + "可在救援页面点击“强制重启进入救援”(强制断电后从救援配置开机)," + "也可以手动“强制断电”后再点“开机”。" + "普通“强制重置”只重置运行中的 QEMU,不会加载新的启动配置;" + "强制断电可能导致未保存数据丢失" + ) + else: + next_step = ( + "原系统启动配置尚未恢复。请先刷新虚拟机状态;如仍在运行," + "可通过救援系统的 VNC 控制台手动关机,待显示已关机后重试退出救援" + ) + try: + domain.shutdown() + except libvirt.libvirtError as exc: + raise VMError( + f"无法请求虚拟机正常关机,{phase}尚未完成;面板未强制断电。{next_step}", + 409, + ) from exc + deadline = time.monotonic() + REINSTALL_SHUTDOWN_TIMEOUT + while domain.isActive(): + if time.monotonic() >= deadline: + raise VMError( + f"正常关机超时,{phase}尚未完成;虚拟机可能随后自行关机。" + f"面板未强制断电。{next_step}", 409) + time.sleep(REINSTALL_SHUTDOWN_POLL_INTERVAL) + + def prepare_rescue_vm(self, vm_id: str, rescue_volume_name: str) -> str: + """Return inactive XML for durable storage before changing this VM.""" + with _CREATE_LOCK, self._connect() as conn: + self._rescue_volume(conn, rescue_volume_name) + return self._rescue_vm_preflight(self._domain(conn, vm_id)) + + def enter_rescue_vm(self, vm_id: str, rescue_volume_name: str, + original_xml: str, *, + progress: Callable[[str], None] | None = None) -> dict[str, Any]: + """Stage a durable rescue boot, gracefully stop, then start the ISO.""" + def phase(value: str) -> None: + if progress is not None: + progress(value) + + with _CREATE_LOCK, self._connect() as conn: + vm_uuid = self._uuid(vm_id) + domain = self._domain(conn, vm_uuid) + current_xml = self._rescue_vm_preflight(domain) + if not self._rescue_xml_matches(current_xml, original_xml): + raise VMError("虚拟机配置已变化,请重新提交救援操作", 409) + pool, volume = self._rescue_volume(conn, rescue_volume_name) + original_autostart = bool(domain.autostart()) + rescue_xml = self._rescue_xml( + original_xml, vm_uuid, rescue_volume_name, + self._volume_source(pool, volume), original_autostart) + was_running = bool(domain.isActive()) + switched = False + rescue_domain = None + try: + phase("mounting") + rescue_domain = conn.defineXML(rescue_xml) + if rescue_domain is None: + raise VMError("宿主机未能保存救援启动配置", 502) + switched = True + self._restore_rescue_autostart(rescue_domain, original_autostart) + staged_xml = rescue_domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + except Exception as exc: + restored = True + if switched: + try: + restored_domain = conn.defineXML(original_xml) + if restored_domain is None: + raise VMError("宿主机未能恢复原虚拟机配置", 502) + self._restore_rescue_autostart(restored_domain, original_autostart) + except Exception: + LOG.exception("Could not restore original VM XML for %s", vm_uuid) + restored = False + if not restored: + raise VMError( + "救援 ISO 预挂载失败且原虚拟机持久配置未能恢复;" + "没有强制断电,请检查宿主机", 502, + ) from exc + raise VMError("救援 ISO 预挂载失败,原虚拟机未受影响", 502) from exc + + phase("shutting_down") + try: + self._wait_for_rescue_shutdown(domain, "救援启动") + except VMError as exc: + if domain.isActive(): + vm = self._vm_dict(domain) + if vm["rescue_mode"] and not vm["rescue_staged"]: + # The guest may have shut down and been cold-started + # by an external actor while the request timed out. + return {"vm": vm, "warning": + "救援配置已运行,但宿主机关机状态返回异常;请通过 VNC 确认已进入救援系统"} + # Never discard the persistent rescue boot here: the user + # can safely decide whether to power-cycle manually. + phase("pending_manual_restart") + return {"vm": vm, + "pending_manual_restart": True, + "warning": str(exc)} + # The guest stopped after the error; continue with a cold + # start from the already-staged rescue definition. + latest_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + if not self._rescue_xml_matches(latest_xml, staged_xml): + raise VMError("关机后救援启动配置已变化,救援已停止;请检查虚拟机状态", 409) + try: + phase("starting") + rescue_domain.create() + except Exception as exc: + if switched and rescue_domain is not None: + try: + if rescue_domain.isActive() and self._vm_dict(rescue_domain)["rescue_mode"]: + phase("completed") + return {"vm": self._vm_dict(rescue_domain), + "warning": "救援系统可能已启动,但宿主机启动返回错误;请检查控制台"} + except Exception: + LOG.exception("Could not inspect rescue VM %s after start error", vm_uuid) + restored = True + restart_domain = domain + if switched: + try: + restored_domain = conn.defineXML(original_xml) + if restored_domain is None: + raise VMError("宿主机未能恢复原虚拟机配置", 502) + self._restore_rescue_autostart(restored_domain, original_autostart) + restart_domain = restored_domain + except Exception: + LOG.exception("Could not restore original VM XML for %s", vm_uuid) + restored = False + if restored and was_running: + try: + restart_domain.create() + except Exception: + LOG.exception("Could not restart original VM %s after rescue failure", vm_uuid) + restored = False + if not restored: + raise VMError( + "救援启动失败且原虚拟机未能完全恢复;没有强制断电,请检查宿主机", 502, + ) from exc + raise VMError("救援启动失败,已恢复原虚拟机配置及运行状态", 502) from exc + phase("completed") + return {"vm": self._vm_dict(rescue_domain)} + + def force_start_staged_rescue_vm(self, vm_id: str, + original_xml: str) -> dict[str, Any]: + """Cold power-cycle only a verified, pre-staged rescue VM. + + libvirt's reset() acts on the live QEMU process and cannot load a + changed inactive boot definition. destroy()+create() deliberately + stops that process and starts a new one from the persistent XML. + """ + with _CREATE_LOCK, self._connect() as conn: + vm_uuid = self._uuid(vm_id) + domain = self._domain(conn, vm_uuid) + if not domain.isPersistent(): + raise VMError("救援虚拟机不是持久化定义,不能强制重启", 409) + try: + original_root = ET.fromstring(original_xml) + except (TypeError, ET.ParseError) as exc: + raise VMError("原虚拟机配置备份无效", 409) from exc + if (original_root.findtext("uuid") != vm_uuid + or original_root.find(f"./metadata/{{{PANEL_NS}}}rescue") is not None): + raise VMError("原虚拟机配置备份与目标虚拟机不匹配", 409) + try: + staged_root = ET.fromstring( + domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + except ET.ParseError as exc: + raise VMError("救援虚拟机持久配置 XML 无效", 502) from exc + marker = staged_root.find(f"./metadata/{{{PANEL_NS}}}rescue") + if (marker is None or marker.get("original-sha256") != + self._rescue_original_hash(original_xml) + or not RESCUE_VOLUME_RE.fullmatch(marker.get("volume", "")) + or marker.get("original-autostart") not in {"0", "1"}): + raise VMError("救援预挂载记录与原配置备份不匹配,已拒绝强制重启", 409) + if domain.isActive() and self._vm_xml(domain).find( + f"./metadata/{{{PANEL_NS}}}rescue") is not None: + raise VMError("虚拟机已从救援配置运行,无需再次强制重启", 409) + pool, volume = self._rescue_volume(conn, marker.get("volume")) + source_type, source_attrs = self._volume_source(pool, volume) + if not any( + disk.get("type") == source_type + and disk.find("source") is not None + and all(disk.find("source").get(key) == value + for key, value in source_attrs.items()) + and disk.find("boot") is not None + and disk.find("boot").get("order") == "1" + for disk in staged_root.findall("./devices/disk[@device='cdrom']")): + raise VMError("救援 ISO 启动设备与预挂载记录不匹配,已拒绝强制重启", 409) + if domain.isActive(): + try: + domain.destroy() + except libvirt.libvirtError as exc: + if domain.isActive(): + raise VMError("强制断电失败;救援配置已保留,请检查虚拟机状态", 502) from exc + try: + domain.create() + except libvirt.libvirtError as exc: + try: + vm = self._vm_dict(domain) + if (vm["state"] == "running" and vm["rescue_mode"] + and not vm["rescue_staged"]): + return {"vm": vm, + "warning": "救援系统可能已启动,但宿主机返回错误;请检查控制台"} + except Exception: + LOG.exception("Could not inspect staged rescue VM %s after start error", vm_uuid) + raise VMError( + "救援系统强制重启后未能启动;救援 ISO 配置已保留," + "可重试开机或取消救援。强制断电可能导致未保存数据丢失", 502, + ) from exc + vm = self._vm_dict(domain) + if not domain.isActive() or not vm["rescue_mode"] or vm["rescue_staged"]: + raise VMError( + "已尝试强制启动,但救援系统未进入运行状态;" + "救援 ISO 配置已保留,请检查控制台或重试开机", 502, + ) + return {"vm": vm} + + def exit_rescue_vm(self, vm_id: str, original_xml: str, *, + progress: Callable[[str], None] | None = None) -> dict[str, Any]: + """Gracefully stop rescue mode, restore original XML, and start OS.""" + def phase(value: str) -> None: + if progress is not None: + progress(value) + + with _CREATE_LOCK, self._connect() as conn: + vm_uuid = self._uuid(vm_id) + domain = self._domain(conn, vm_uuid) + if not domain.isPersistent(): + raise VMError("救援虚拟机不是持久化定义,无法恢复", 409) + try: + original_root = ET.fromstring(original_xml) + except (TypeError, ET.ParseError) as exc: + raise VMError("原虚拟机配置备份无效", 409) from exc + if (original_root.findtext("uuid") != vm_uuid + or original_root.find(f"./metadata/{{{PANEL_NS}}}rescue") is not None): + raise VMError("原虚拟机配置备份与目标虚拟机不匹配", 409) + rescue_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + try: + rescue_root = ET.fromstring(rescue_xml) + except ET.ParseError as exc: + raise VMError("救援虚拟机配置 XML 无效", 502) from exc + marker = rescue_root.find(f"./metadata/{{{PANEL_NS}}}rescue") + if (marker is None or marker.get("original-sha256") != + self._rescue_original_hash(original_xml) + or not RESCUE_VOLUME_RE.fullmatch(marker.get("volume", "")) + or marker.get("original-autostart") not in {"0", "1"}): + raise VMError("虚拟机救援标记与原配置备份不匹配,已停止恢复", 409) + staged_running = False + if domain.isActive(): + live_marker = self._vm_xml(domain).find( + f"./metadata/{{{PANEL_NS}}}rescue") + staged_running = live_marker is None + if (live_marker is not None + and (live_marker.get("original-sha256") != + marker.get("original-sha256") + or live_marker.get("volume") != marker.get("volume"))): + raise VMError("虚拟机当前并未从已记录的救援配置运行,已停止恢复", 409) + original_autostart = marker.get("original-autostart") == "1" + rescue_autostart = bool(domain.autostart()) + if staged_running: + # Rescue was saved for the next cold boot, but the original + # guest is still running. Cancelling the staged boot must not + # shut down or restart that guest. + switched = False + try: + phase("restoring") + normal_domain = conn.defineXML(original_xml) + if normal_domain is None: + raise VMError("宿主机未能恢复原虚拟机配置", 502) + switched = True + self._restore_rescue_autostart(normal_domain, original_autostart) + except Exception as exc: + if switched: + try: + rescue_domain = conn.defineXML(rescue_xml) + if rescue_domain is None: + raise VMError("宿主机未能恢复救援启动配置", 502) + self._restore_rescue_autostart( + rescue_domain, rescue_autostart) + except Exception: + LOG.exception("Could not restore staged rescue XML for %s", vm_uuid) + raise VMError( + "取消救援预挂载失败,原虚拟机仍在运行,但持久配置状态不确定;" + "请检查宿主机", 502, + ) from exc + raise VMError("取消救援预挂载失败,原虚拟机仍在运行", 502) from exc + phase("completed") + return {"vm": self._vm_dict(normal_domain)} + was_running = bool(domain.isActive()) + phase("shutting_down") + self._wait_for_rescue_shutdown(domain, "退出救援") + latest_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + if not self._rescue_xml_matches(latest_xml, rescue_xml): + raise VMError("关机后救援配置已变化,退出救援已停止;请检查虚拟机状态", 409) + switched = False + normal_domain = None + try: + phase("starting") + normal_domain = conn.defineXML(original_xml) + if normal_domain is None: + raise VMError("宿主机未能恢复原虚拟机配置", 502) + switched = True + self._restore_rescue_autostart(normal_domain, original_autostart) + normal_domain.create() + except Exception as exc: + if switched and normal_domain is not None: + try: + if normal_domain.isActive() and not self._vm_dict(normal_domain)["rescue_mode"]: + phase("completed") + return {"vm": self._vm_dict(normal_domain), + "warning": "原系统可能已启动,但宿主机启动返回错误;请检查控制台"} + except Exception: + LOG.exception("Could not inspect VM %s after rescue exit error", vm_uuid) + restored = True + restart_domain = domain + if switched: + try: + restored_domain = conn.defineXML(rescue_xml) + if restored_domain is None: + raise VMError("宿主机未能恢复救援启动配置", 502) + self._restore_rescue_autostart(restored_domain, rescue_autostart) + restart_domain = restored_domain + except Exception: + LOG.exception("Could not restore rescue VM XML for %s", vm_uuid) + restored = False + if restored and was_running: + try: + restart_domain.create() + except Exception: + LOG.exception("Could not restart rescue VM %s after exit failure", vm_uuid) + restored = False + if not restored: + raise VMError( + "退出救援失败且救援虚拟机未能完全恢复;没有强制断电,请检查宿主机", 502, + ) from exc + raise VMError("退出救援失败,已恢复救援启动配置及运行状态", 502) from exc + phase("completed") + vm = self._vm_dict(normal_domain) + if vm["rescue_mode"]: + raise VMError("原系统已启动但仍显示救援模式,请检查虚拟机配置", 502) + return {"vm": vm} + + @staticmethod + def _mac_for_new_vm(conn: Any) -> str: + used = { + (node.get("address") or "").lower() + for domain in conn.listAllDomains(0) + for node in VMService._vm_xml(domain).findall("./devices/interface/mac") + } + for _ in range(32): + mac = "52:54:00:" + ":".join(f"{byte:02x}" for byte in secrets.token_bytes(3)) + if mac not in used: + return mac + raise VMError("无法生成不重复的虚拟网卡 MAC", 503) + + def _cloud_domain_xml(self, spec: dict[str, Any], vm_uuid: str, + disk_name: str, disk_source: tuple[str, dict[str, str]], + seed_name: str, seed_source: tuple[str, dict[str, str]], + mac: str, public_ip_cidr: str) -> str: + root = ET.fromstring(self._domain_xml( + spec, vm_uuid, disk_name, disk_source, ("file", {}), + install_phase=False)) + interface = root.find("./devices/interface") + if interface is None: + raise VMError("无法生成虚拟网卡配置", 500) + interface.insert(0, ET.Element("mac", address=mac)) + cdrom = root.find("./devices/disk[@device='cdrom']") + if cdrom is None: + raise VMError("无法生成 cloud-init 配置盘", 500) + cdrom.set("type", seed_source[0]) + target = cdrom.find("target") + source = ET.Element("source", **seed_source[1]) + if target is not None: + cdrom.insert(list(cdrom).index(target), source) + else: + cdrom.append(source) + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + if managed is None: + raise VMError("无法生成面板元数据", 500) + managed.set("seed-volume", seed_name) + managed.set("public-ip-cidr", public_ip_cidr) + managed.set("os-source", "cloud_template") + if spec.get("os_name") is not None: + managed.set("os-name", spec["os_name"]) + return ET.tostring(root, encoding="unicode") + + def create_cloud_vm(self, spec: dict[str, Any], template_volume_name: str) -> dict[str, Any]: + """Clone a trusted cloud image and supply static public networking.""" + validated = self._validate_common_create(spec) + validated["created_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + validated["os_name"] = self._validated_os_name(spec.get("os_name")) + requested_uuid = spec.get("vm_uuid") + if requested_uuid is not None: + try: + requested_uuid = str(uuidlib.UUID(requested_uuid)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效") from exc + if self.bridge_name is None: + raise VMError("公网模板创建需要先在宿主机设置 Linux 网桥,例如 bridge:br0", 409) + if not TEMPLATE_VOLUME_RE.fullmatch(template_volume_name): + raise VMError("只能使用面板导入的云镜像模板") + try: + network = validate_cloud_network( + spec.get("public_ip_cidr"), spec.get("gateway"), + spec.get("dns_servers"), spec.get("guest_ssh_public_key", ""), + spec.get("root_password_hash")) + except ValueError as exc: + raise VMError(str(exc)) from exc + + with _CREATE_LOCK, self._connect() as conn: + domains = conn.listAllDomains(0) + if any(domain.name() == validated["name"] for domain in domains): + raise VMError("虚拟机名称已存在", 409) + for domain in domains: + managed = self._vm_xml(domain).find(f"./metadata/{{{PANEL_NS}}}managed") + if managed is not None and managed.get("public-ip-cidr", "").split("/")[0] == \ + network["public_ip_cidr"].split("/")[0]: + raise VMError("该公网 IP 已分配给面板中的另一台虚拟机", 409) + if conn.getInfo()[0] != "x86_64": + raise VMError("当前云镜像模板仅支持 x86_64 宿主机", 422) + pool = self._active_pool(conn, self.storage_pool) + self._refresh_directory_pool(pool) + if template_volume_name not in pool.listVolumes(): + raise VMError("模板卷在宿主机上不存在,请重新导入", 404) + template = pool.storageVolLookupByName(template_volume_name) + template_xml = ET.fromstring(template.XMLDesc(0)) + if template_xml.find("./target/format") is None or \ + template_xml.find("./target/format").get("type") != "qcow2": + raise VMError("模板卷不是 qcow2 格式", 409) + template_capacity = int(template.info()[1]) + target_capacity = validated["disk_gib"] * GIB + if target_capacity < template_capacity: + raise VMError("虚拟磁盘不能小于云镜像模板的原始容量", 409) + if target_capacity > pool.info()[3]: + raise VMError("存储池剩余空间不足", 409) + vm_uuid = requested_uuid or str(uuidlib.uuid4()) + disk_name = f"{validated['name']}.qcow2" + seed_name = f"panel-seed-{vm_uuid}.iso" + if disk_name in pool.listVolumes() or seed_name in pool.listVolumes(): + raise VMError("同名虚拟磁盘或配置盘已存在,不会覆盖", 409) + mac = self._mac_for_new_vm(conn) + try: + seed_data = build_seed_iso(vm_uuid, validated["name"], mac, network) + except ImportError as exc: + raise VMError("面板缺少 pycdlib,需安装 requirements.txt 中的依赖", 503) from exc + created: list[tuple[Any, str]] = [] + try: + disk = pool.createXMLFrom(self._volume_xml_bytes( + disk_name, template_capacity, "qcow2"), template, 0) + if disk is None: + raise VMError("宿主机未能克隆云镜像模板", 502) + created.append((disk, disk_name)) + if target_capacity > template_capacity: + disk.resize(target_capacity, 0) + seed = pool.createXML(self._volume_xml_bytes( + seed_name, len(seed_data), "raw"), 0) + if seed is None: + raise VMError("宿主机未能创建 cloud-init 配置盘", 502) + created.append((seed, seed_name)) + self._upload_volume(conn, seed, iter((seed_data,)), len(seed_data)) + disk_source = self._volume_source(pool, disk) + seed_source = self._volume_source(pool, seed) + domain_xml = self._cloud_domain_xml( + validated, vm_uuid, disk_name, disk_source, + seed_name, seed_source, mac, network["public_ip_cidr"]) + domain = conn.defineXML(domain_xml) + if domain is None: + raise VMError("宿主机未能定义云镜像虚拟机", 502) + self._enable_vm_autostart(domain) + domain.create() + return self._vm_dict(domain) + except Exception as exc: + clean = True + for volume, volume_name in reversed(created): + if not self._rollback_new_vm(conn, vm_uuid, validated["name"], + pool, volume, volume_name): + clean = False + break + if not clean: + raise VMError( + f"云虚拟机创建失败且回滚不完整;已保留相关文件,请检查 {validated['name']}", + 502, + ) from exc + if isinstance(exc, VMError): + raise + LOG.warning("Could not create cloud VM %s: %s", validated["name"], exc) + raise VMError("无法创建云镜像虚拟机,请检查网桥、磁盘权限和宿主机日志", 502) from exc + + def reinstall_cloud_vm( + self, + vm_id: str, + template_volume_name: str, + *, + os_name: str | None = None, + ssh_public_key: str = "", + root_password_hash: str | None = None, + progress: Callable[[str], None] | None = None, + ) -> dict[str, Any]: + """Replace one panel cloud VM's disk after a graceful shutdown. + + The old disk remains untouched until the replacement domain has + started. Failure before that point restores the old definition and + retains the old disk. A cleanup failure after start is a warning, not + a rollback: some old volumes may already have been removed. + """ + if not TEMPLATE_VOLUME_RE.fullmatch(template_volume_name): + raise VMError("只能使用面板导入的云镜像模板") + os_name = self._validated_os_name(os_name) + if self.bridge_name is None: + raise VMError("公网模板重装需要原 Linux 网桥配置", 409) + + def phase(value: str) -> None: + if progress is not None: + progress(value) + + with _CREATE_LOCK, self._connect() as conn: + domain = self._domain(conn, vm_id) + if not domain.isPersistent(): + raise VMError("只能重装持久化虚拟机", 409) + if getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0): + raise VMError("虚拟机存在托管保存状态,请先处理后再重装", 409) + if domain.snapshotNum(0) > 0: + raise VMError("虚拟机存在快照,请先处理后再重装", 409) + original_root = self._vm_xml(domain) + managed = original_root.find(f"./metadata/{{{PANEL_NS}}}managed") + if (managed is None or managed.get("version") != "2" + or not managed.get("seed-volume") + or not managed.get("public-ip-cidr")): + raise VMError("只有面板创建的公网云镜像虚拟机可以自动重装", 409) + disks = original_root.findall("./devices/disk[@device='disk']") + cdroms = original_root.findall("./devices/disk[@device='cdrom']") + interfaces = original_root.findall("./devices/interface") + if len(disks) != 1 or len(cdroms) != 1 or len(interfaces) != 1: + raise VMError("虚拟机磁盘或网卡配置已变化,不能安全自动重装", 409) + interface = interfaces[0] + source = interface.find("source") + mac_node = interface.find("mac") + if (interface.get("type") != "bridge" or source is None + or source.get("bridge") != self.bridge_name + or mac_node is None or not mac_node.get("address")): + raise VMError("虚拟机网桥或 MAC 已变化,不能自动沿用原网络", 409) + mac = mac_node.get("address").lower() + old_disk = self._owned_volume(conn, domain) + old_seed = self._owned_seed_volume(conn, domain) + if old_seed is None: + raise VMError("找不到原 cloud-init 配置盘", 409) + try: + original_network = read_seed_network(self._download_seed_volume(conn, old_seed)) + network = validate_cloud_network( + original_network["public_ip_cidr"], original_network["gateway"], + original_network["dns_servers"], ssh_public_key, root_password_hash, + ) + except (ImportError, ValueError) as exc: + raise VMError("无法校验原 cloud-init 网络配置,已停止重装", 409) from exc + if (original_network["mac"] != mac + or network["public_ip_cidr"] != managed.get("public-ip-cidr")): + raise VMError("原配置盘的公网 IP 或 MAC 与虚拟机不一致,已停止重装", 409) + + pool = self._active_pool(conn, self.storage_pool) + self._refresh_directory_pool(pool) + if template_volume_name not in pool.listVolumes(): + raise VMError("模板卷在宿主机上不存在,请重新导入", 404) + template = pool.storageVolLookupByName(template_volume_name) + template_format = ET.fromstring(template.XMLDesc(0)).find("./target/format") + if template_format is None or template_format.get("type") != "qcow2": + raise VMError("模板卷不是 qcow2 格式", 409) + target_capacity = int(old_disk.info()[1]) + template_capacity = int(template.info()[1]) + if template_capacity > target_capacity: + raise VMError("所选模板容量超过原系统盘,无法保留原磁盘大小", 409) + if target_capacity > pool.info()[3]: + raise VMError("存储池空间不足,无法创建新系统盘", 409) + + phase("shutting_down") + if domain.isActive(): + domain.shutdown() + deadline = time.monotonic() + REINSTALL_SHUTDOWN_TIMEOUT + while domain.isActive(): + if time.monotonic() >= deadline: + raise VMError("正常关机超时,重装已停止;旧系统盘未改变", 409) + time.sleep(REINSTALL_SHUTDOWN_POLL_INTERVAL) + + # Inspect the now-inactive definition again, so a concurrent + # external edit cannot quietly alter the storage or network. + old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + inactive_root = ET.fromstring(old_xml) + inactive_managed = inactive_root.find(f"./metadata/{{{PANEL_NS}}}managed") + inactive_interface = inactive_root.find("./devices/interface") + inactive_mac = (inactive_interface.find("mac") if inactive_interface is not None + else None) + inactive_source = (inactive_interface.find("source") + if inactive_interface is not None else None) + if (inactive_managed is None + or inactive_managed.get("disk-volume") != old_disk.name() + or inactive_managed.get("seed-volume") != old_seed.name() + or inactive_managed.get("public-ip-cidr") != network["public_ip_cidr"] + or inactive_mac is None or (inactive_mac.get("address") or "").lower() != mac + or inactive_source is None + or inactive_source.get("bridge") != self.bridge_name): + raise VMError("关机后虚拟机配置已变化,重装已停止", 409) + if self._owned_volume(conn, domain).name() != old_disk.name() or \ + self._owned_seed_volume(conn, domain).name() != old_seed.name(): + raise VMError("关机后存储卷已变化,重装已停止", 409) + + disk_name = f"panel-r-{uuidlib.uuid4().hex}.qcow2" + seed_uuid = str(uuidlib.uuid4()) + seed_name = f"panel-seed-{seed_uuid}.iso" + if disk_name in pool.listVolumes() or seed_name in pool.listVolumes(): + raise VMError("新系统盘或配置盘名称冲突,已停止重装", 409) + try: + seed_data = build_seed_iso(seed_uuid, domain.name(), mac, network) + except ImportError as exc: + raise VMError("面板缺少 pycdlib,需安装 requirements.txt 中的依赖", 503) from exc + created: list[Any] = [] + switched = False + phase("cloning") + try: + disk = pool.createXMLFrom(self._volume_xml_bytes( + disk_name, template_capacity, "qcow2"), template, 0) + if disk is None: + raise VMError("宿主机未能克隆新系统盘", 502) + created.append(disk) + if target_capacity > template_capacity: + disk.resize(target_capacity, 0) + seed = pool.createXML(self._volume_xml_bytes( + seed_name, len(seed_data), "raw"), 0) + if seed is None: + raise VMError("宿主机未能创建新配置盘", 502) + created.append(seed) + self._upload_volume(conn, seed, iter((seed_data,)), len(seed_data)) + + new_root = ET.fromstring(old_xml) + for device, volume in (("disk", disk), ("cdrom", seed)): + node = new_root.find(f"./devices/disk[@device='{device}']") + if node is None: + raise VMError("虚拟机磁盘配置已变化,无法切换", 409) + source_type, source_attrs = self._volume_source(pool, volume) + node.set("type", source_type) + old_source = node.find("source") + if old_source is None: + raise VMError("虚拟机磁盘来源已变化,无法切换", 409) + source_index = list(node).index(old_source) + node.remove(old_source) + node.insert(source_index, ET.Element("source", **source_attrs)) + new_managed = new_root.find(f"./metadata/{{{PANEL_NS}}}managed") + if new_managed is None: + raise VMError("虚拟机面板元数据已变化,无法切换", 409) + new_managed.set("disk-volume", disk_name) + new_managed.set("seed-volume", seed_name) + # A different reinstall template invalidates the old label. + new_managed.attrib.pop("os-source", None) + new_managed.attrib.pop("os-name", None) + new_managed.attrib.pop("install-iso", None) + new_managed.set("os-source", "cloud_template") + if os_name is not None: + new_managed.set("os-name", os_name) + phase("starting") + new_domain = conn.defineXML(ET.tostring(new_root, encoding="unicode")) + if new_domain is None: + raise VMError("宿主机未能切换虚拟机定义", 502) + switched = True + new_domain.create() + except Exception as exc: + if switched: + try: + if new_domain.isActive(): + live_managed = self._vm_xml(new_domain).find( + f"./metadata/{{{PANEL_NS}}}managed") + if live_managed is not None and \ + live_managed.get("disk-volume") == disk_name: + # A transport error can occur after QEMU has + # actually started. Keep both generations and + # report the new credential instead of + # restoring only the inactive definition. + LOG.error("VM %s may have started on replacement disk after error", + vm_id, exc_info=True) + phase("completed") + return { + "vm": {"uuid": vm_id, + "name": inactive_root.findtext("name") or vm_id, + "state": "running"}, + "warning": "新系统可能已启动,但启动返回错误;旧系统盘已保留," + "请检查虚拟机状态和存储卷后手工清理", + } + except Exception: + LOG.exception("Could not inspect VM %s after start error", vm_id) + restored = True + if switched: + try: + conn.defineXML(old_xml) + except Exception: + LOG.exception("Could not restore original definition for %s", vm_id) + restored = False + if restored: + for volume in reversed(created): + try: + if self._other_domain_uses_volume( + conn, "", pool.name(), volume.name(), volume.path()): + restored = False + continue + volume.delete(0) + except Exception: + LOG.exception("Could not remove replacement volume %s", volume.name()) + restored = False + if not restored: + raise VMError( + "重装失败且自动回滚不完整;旧系统盘已保留,请检查虚拟机与新建存储卷", + 502, + ) from exc + if isinstance(exc, VMError): + raise + LOG.warning("Could not reinstall VM %s: %s", vm_id, exc) + raise VMError("重装失败,已恢复原虚拟机定义及旧系统盘", 502) from exc + + # QEMU started with the new disk. This does not prove the guest + # booted or has working SSH; the operator explicitly selected + # automatic removal of the old disk after this point. + phase("cleaning_up") + warnings = [] + for volume in (old_seed, old_disk): + try: + if self._other_domain_uses_volume( + conn, "", pool.name(), volume.name(), volume.path()): + warnings.append(f"旧存储卷 {volume.name()} 仍被引用,未删除") + continue + volume.delete(0) + except Exception: + LOG.exception("Reinstalled VM %s, but old volume %s remains", vm_id, + volume.name()) + warnings.append(f"旧存储卷 {volume.name()} 删除失败,请检查宿主机") + try: + vm_state = self._vm_dict(new_domain) + except Exception: + LOG.exception("VM %s started after reinstall, but its details could not be read", vm_id) + vm_state = {"uuid": vm_id, "name": inactive_root.findtext("name") or vm_id, + "state": "running"} + warnings.append("新系统已启动,但面板未能读取完整虚拟机状态,请检查宿主机") + result: dict[str, Any] = {"vm": vm_state, "credential_generation": seed_name} + if warnings: + result["warning"] = ";".join(warnings) + phase("completed") + return result + + def create_vm(self, spec: dict[str, Any]) -> dict[str, Any]: + validated = self._validate_create(spec) + validated["created_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + requested_uuid = spec.get("vm_uuid") + if requested_uuid is not None: + try: + requested_uuid = str(uuidlib.UUID(requested_uuid)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效") from exc + with self._connect() as conn: + if any(domain.name() == validated["name"] for domain in conn.listAllDomains(0)): + raise VMError("虚拟机名称已存在", 409) + host_arch = conn.getInfo()[0] + if host_arch != "x86_64": + raise VMError("当前创建模板只支持 x86_64 宿主机", 422) + disk_pool = self._active_pool(conn, self.storage_pool) + self._refresh_directory_pool(disk_pool) + if validated["disk_gib"] * GIB > disk_pool.info()[3]: + raise VMError("存储池剩余空间不足", 409) + iso_pool = self._active_pool(conn, self.iso_pool) + self._refresh_directory_pool(iso_pool) + if validated["iso"] not in iso_pool.listVolumes(): + raise VMError("安装镜像不在配置的 ISO 存储池中", 404) + if self.bridge_name is None: + network = conn.networkLookupByName(self.network) + if not network.isActive(): + raise VMError("配置的虚拟网络未启动", 409) + + vm_uuid = requested_uuid or str(uuidlib.uuid4()) + disk_name = f"{validated['name']}.qcow2" + if disk_name in disk_pool.listVolumes(): + raise VMError(f"磁盘文件 {disk_name} 已存在,不会覆盖现有数据", 409) + iso_volume = iso_pool.storageVolLookupByName(validated["iso"]) + iso_source = self._volume_source(iso_pool, iso_volume) + volume = disk_pool.createXML(self._volume_xml(disk_name, validated["disk_gib"]), 0) + try: + disk_source = self._volume_source(disk_pool, volume) + install_xml = self._domain_xml( + validated, vm_uuid, disk_name, disk_source, iso_source, + install_phase=True) + final_xml = self._domain_xml( + validated, vm_uuid, disk_name, disk_source, iso_source, + install_phase=False) + try: + install_domain = conn.createXML(install_xml, 0) + except libvirt.libvirtError as exc: + LOG.warning("Could not start installation VM %s: %s", validated["name"], exc) + bridge_hint = f"网桥 {self.bridge_name}、" if self.bridge_name else "" + raise VMError( + f"无法启动安装期虚拟机;请检查 {bridge_hint}Q35/UEFI 固件、" + "磁盘和 ISO 访问权限,并查看宿主机 libvirt 日志", 409, + ) from exc + if install_domain is None: + raise VMError("宿主机未能启动安装期虚拟机", 502) + # Like virt-install, keep the live installation XML separate + # from the persistent definition used after the first stop. + try: + domain = conn.defineXML(final_xml) + except libvirt.libvirtError as exc: + LOG.warning("Could not persist final VM %s: %s", validated["name"], exc) + raise VMError("安装期虚拟机已启动,但无法保存卸载 ISO 后的配置", 502) from exc + if domain is None: + raise VMError("宿主机未能保存卸载 ISO 后的虚拟机配置", 502) + self._enable_vm_autostart(domain) + return self._vm_dict(domain) + except Exception as exc: + if not self._rollback_new_vm(conn, vm_uuid, validated["name"], + disk_pool, volume, disk_name): + raise VMError( + "创建失败且自动回滚不完整;为避免误删运行中磁盘,请检查宿主机中的" + f"虚拟机 {validated['name']} 和磁盘 {disk_name}", 502, + ) from exc + raise + + def action(self, uuid: str, action: str) -> dict[str, Any]: + methods = { + "start": "create", + "shutdown": "shutdown", + "reboot": "reboot", + "poweroff": "destroy", + "reset": "reset", + } + if action not in methods: + raise VMError("不支持的虚拟机操作") + with self._connect() as conn: + domain = self._domain(conn, uuid) + active = bool(domain.isActive()) + if action == "start" and active: + raise VMError("虚拟机已经在运行", 409) + if action != "start" and not active: + raise VMError("虚拟机未运行", 409) + if action == "reset": + domain.reset(0) + else: + getattr(domain, methods[action])() + return self._vm_dict(domain) + + @staticmethod + def _disk_sources(root: ET.Element) -> list[ET.Element]: + return [source for disk in root.findall("./devices/disk") + if disk.get("device") == "disk" + for source in [disk.find("source")] if source is not None] + + @staticmethod + def _all_disk_sources(root: ET.Element) -> list[ET.Element]: + # Include primary, backing, external data-file and mirror sources. A + # second VM can depend on this volume in any of those positions. + return root.findall("./devices/disk//source") + + def _other_domain_uses_volume(self, conn: Any, vm_uuid: str, + pool_name: str, volume_name: str, + volume_path: str) -> bool: + for other in conn.listAllDomains(0): + if other.UUIDString() == vm_uuid: + continue + flags = [0] + if other.isActive() and other.isPersistent(): + flags.append(libvirt.VIR_DOMAIN_XML_INACTIVE) + for flag in flags: + try: + root = ET.fromstring(other.XMLDesc(flag)) + except ET.ParseError as exc: + raise VMError("其他虚拟机配置 XML 无效,无法安全删除磁盘", 502) from exc + for source in self._all_disk_sources(root): + if ((source.get("pool") == pool_name + and source.get("volume") == volume_name) + or volume_path in (source.get("file"), source.get("dev"))): + return True + return False + + def _owned_volume(self, conn: Any, domain: Any) -> Any: + root = self._vm_xml(domain) + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + if managed is None: + raise VMError("只能删除由面板创建的磁盘", 403) + disk_name = managed.get("disk-volume") or f"panel-{domain.UUIDString()}.qcow2" + if (not disk_name.endswith(".qcow2") or "/" in disk_name + or not NAME_RE.fullmatch(disk_name.removesuffix(".qcow2"))): + raise VMError("面板记录的磁盘文件名无效,无法安全删除", 409) + pool = self._active_pool(conn, self.storage_pool) + pool_name = pool.name() + volume = pool.storageVolLookupByName(disk_name) + volume_path = volume.path() + sources = self._disk_sources(root) + if len(sources) != 1: + raise VMError("虚拟机磁盘配置已变化,无法安全删除磁盘", 409) + source = sources[0] + volume_source = (source.get("pool") == pool_name + and source.get("volume") == disk_name) + file_source = source.get("file") == volume_path + if not (volume_source or file_source): + raise VMError("虚拟机磁盘不属于面板配置的存储池", 409) + if self._other_domain_uses_volume(conn, domain.UUIDString(), + pool_name, disk_name, volume_path): + raise VMError("磁盘还被其他虚拟机使用", 409) + if domain.snapshotNum(0) > 0: + raise VMError("虚拟机有快照,请先处理快照再删除磁盘", 409) + return volume + + def _owned_seed_volume(self, conn: Any, domain: Any) -> Any | None: + root = self._vm_xml(domain) + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + seed_name = managed.get("seed-volume") if managed is not None else None + if seed_name is None: + return None + if not re.fullmatch( + r"panel-seed-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-" + r"[0-9a-f]{4}-[0-9a-f]{12}\.iso", seed_name or ""): + raise VMError("面板记录的 cloud-init 配置盘名称无效", 409) + pool = self._active_pool(conn, self.storage_pool) + volume = pool.storageVolLookupByName(seed_name) + volume_path = volume.path() + sources = [source for cdrom in root.findall("./devices/disk[@device='cdrom']") + for source in [cdrom.find("source")] if source is not None] + if len(sources) != 1: + raise VMError("cloud-init 配置盘已被修改,无法安全删除", 409) + source = sources[0] + if not ((source.get("pool") == pool.name() and source.get("volume") == seed_name) + or source.get("file") == volume_path): + raise VMError("cloud-init 配置盘来源与面板记录不符", 409) + if self._other_domain_uses_volume(conn, domain.UUIDString(), + pool.name(), seed_name, volume_path): + raise VMError("cloud-init 配置盘还被其他虚拟机使用", 409) + return volume + + @staticmethod + def _undefine_domain(domain: Any, *, remove_nvram: bool) -> None: + """Handle UEFI NVRAM when removing a domain definition.""" + if remove_nvram: + flags = getattr(libvirt, "VIR_DOMAIN_UNDEFINE_NVRAM", 0) + if not flags: + # Older bindings cannot request deletion; retain NVRAM so + # undefine still succeeds rather than leaving a partial VM. + flags = getattr(libvirt, "VIR_DOMAIN_UNDEFINE_KEEP_NVRAM", 0) + else: + flags = getattr(libvirt, "VIR_DOMAIN_UNDEFINE_KEEP_NVRAM", 0) + if flags: + domain.undefineFlags(flags) + else: + domain.undefine() + + def delete_vm(self, uuid: str, delete_disks: bool) -> dict[str, Any]: + if not isinstance(delete_disks, bool): + raise VMError("delete_disks 必须是布尔值") + with self._connect() as conn: + domain = self._domain(conn, uuid) + if domain.isActive(): + raise VMError("请先关闭虚拟机,再删除", 409) + if not domain.isPersistent(): + raise VMError("无法删除临时虚拟机定义", 409) + volume = self._owned_volume(conn, domain) if delete_disks else None + seed_volume = self._owned_seed_volume(conn, domain) if delete_disks else None + vm_uuid = domain.UUIDString() + managed = self._vm_xml(domain).find(f"./metadata/{{{PANEL_NS}}}managed") + self._undefine_domain( + domain, remove_nvram=(delete_disks and managed is not None + and managed.get("version") == "2"), + ) + deleted_disks: list[str] = [] + for removable in (seed_volume, volume): + if removable is None: + continue + # Never use WITH_SNAPSHOTS or zeroing flags here. + volume_name = removable.name() + try: + removable.delete(0) + except libvirt.libvirtError as exc: + LOG.exception("Domain %s undefined but volume %s remains", vm_uuid, volume_name) + raise VMError("虚拟机定义已删除,但磁盘删除失败;请在宿主机检查该磁盘", 502) from exc + deleted_disks.append(volume_name) + return {"uuid": vm_uuid, "deleted": True, "deleted_disks": deleted_disks} + + def console_port(self, uuid: str) -> int: + with self._connect() as conn: + domain = self._domain(conn, uuid) + if not domain.isActive(): + raise VMError("请先启动虚拟机,再打开 VNC 控制台", 409) + port = self._vnc_port(self._vm_xml(domain)) + if port is None: + raise VMError("虚拟机没有可用的 VNC 控制台", 409) + return port diff --git a/engine/virsh_panel/metrics.py b/engine/virsh_panel/metrics.py new file mode 100644 index 00000000..4f71958f --- /dev/null +++ b/engine/virsh_panel/metrics.py @@ -0,0 +1,278 @@ +"""Periodic libvirt VM measurements and safe counter-to-rate conversion. + +The collector runs independently of browser visits. A process restart deliberately +loses counter baselines: the first subsequent rate sample is unknown, not zero. +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import math +import re +import threading +import time +import uuid +from dataclasses import dataclass +from typing import Any, Callable, Mapping + + +LOG = logging.getLogger(__name__) +SAMPLE_INTERVAL_SECONDS = 60 +RETENTION_SECONDS = 30 * 24 * 60 * 60 +MAX_QUERY_POINTS = 600 +RANGES = {"1h": 3600, "24h": 24 * 3600, "7d": 7 * 24 * 3600, + "30d": RETENTION_SECONDS} +_COUNTER = re.compile(r"^(block|net)\.(\d+)\.(rd|wr|rx|tx)\.bytes$") +_MEMORY_MAX_AGE_SECONDS = 180 + + +def host_scope(profile: Mapping[str, Any]) -> str: + """Keep VM history when pool settings change, but isolate a new SSH host key.""" + if profile.get("host_id"): + return hashlib.sha256(("virt-cloud/host/" + profile["host_id"]).encode("ascii")).hexdigest() + identity = [profile[key] for key in ("host", "port", "fingerprint")] + if (not isinstance(identity[0], str) or not isinstance(identity[1], int) + or not isinstance(identity[2], str)): + raise ValueError("Host identity is invalid") + raw = json.dumps(identity, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +def query_interval_seconds(window_seconds: int) -> int: + """Epoch-aligned buckets cannot exceed MAX_QUERY_POINTS in any range.""" + if window_seconds <= 0: + raise ValueError("Metric range must be positive") + return max(SAMPLE_INTERVAL_SECONDS, + math.ceil(window_seconds / (MAX_QUERY_POINTS - 1) + / SAMPLE_INTERVAL_SECONDS) * SAMPLE_INTERVAL_SECONDS) + + +def _nonnegative_int(value: Any) -> int | None: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + return None + return value + + +def _device_counters(stats: Mapping[str, Any], group: str, + directions: tuple[str, str]) -> tuple[tuple[tuple[str, str], ...], + dict[str, dict[str, int] | None]]: + count = _nonnegative_int(stats.get(f"{group}.count")) + devices: dict[str, dict[str, int]] = { + str(number): {} for number in range(min(count, 1024)) + } if count is not None else {} + for key, value in stats.items(): + match = _COUNTER.fullmatch(key) + if not match or match.group(1) != group or match.group(3) not in directions: + continue + devices.setdefault(match.group(2), {}) + valid = _nonnegative_int(value) + if valid is not None: + devices[match.group(2)][match.group(3)] = valid + signature = tuple(sorted( + (number, str(stats.get(f"{group}.{number}.name", number))) + for number in devices + )) + counters_by_direction: dict[str, dict[str, int] | None] = {} + for direction in directions: + counters = {number: fields[direction] for number, fields in devices.items() + if direction in fields} + # CD-ROM and unsupported devices may never expose byte counters. Use + # only reporting devices, but _rate() resets if that coverage changes. + counters_by_direction[direction] = counters or None + return signature, counters_by_direction + + +def _memory_mib(stats: Mapping[str, Any], sampled_at: int) -> tuple[float | None, + float | None]: + available = _nonnegative_int(stats.get("balloon.available")) + usable = _nonnegative_int(stats.get("balloon.usable")) + last_update = _nonnegative_int(stats.get("balloon.last-update")) + # The QEMU RSS and balloon.current fields describe host process/allocation, + # not guest-used memory. Only guest balloon statistics can support used MiB. + if (available is None or usable is None or last_update is None + or last_update > sampled_at + SAMPLE_INTERVAL_SECONDS + or sampled_at - last_update > _MEMORY_MAX_AGE_SECONDS + or usable > available): + return None, None + return (available - usable) / 1024, available / 1024 + + +@dataclass(frozen=True) +class RawVMStats: + vm_id: str + generation: int + vcpus: int + values: Mapping[str, Any] + + +@dataclass(frozen=True) +class _Baseline: + monotonic: float + generation: int + vcpus: int + cpu_time: int | None + disk_signature: tuple[tuple[str, str], ...] + disk: Mapping[str, Mapping[str, int] | None] + network_signature: tuple[tuple[str, str], ...] + network: Mapping[str, Mapping[str, int] | None] + + +class MetricSampler: + def __init__(self) -> None: + self._previous: dict[tuple[str, str], _Baseline] = {} + + @staticmethod + def _rate(current: Mapping[str, int] | None, + previous: Mapping[str, int] | None, + seconds: float, same_devices: bool) -> float | None: + if (not same_devices or current is None or previous is None + or seconds <= 0 or current.keys() != previous.keys() + or any(value < previous[name] for name, value in current.items())): + return None + return sum(value - previous[name] for name, value in current.items()) / seconds + + def observe(self, scope: str, raw: RawVMStats, *, timestamp: int, + monotonic: float) -> dict[str, Any]: + vm_id = str(uuid.UUID(raw.vm_id)) + values = raw.values + cpu_time = _nonnegative_int(values.get("cpu.time")) + disk_signature, disk = _device_counters(values, "block", ("rd", "wr")) + network_signature, network = _device_counters(values, "net", ("rx", "tx")) + memory_used, memory_total = _memory_mib(values, timestamp) + key = (scope, vm_id) + previous = self._previous.get(key) + seconds = monotonic - previous.monotonic if previous else 0 + # A long pause means a graph gap rather than a misleading average. + same_run = bool(previous and previous.generation == raw.generation + and previous.vcpus == raw.vcpus + and 0 < seconds <= SAMPLE_INTERVAL_SECONDS * 3) + cpu_percent = None + if (same_run and cpu_time is not None and previous.cpu_time is not None + and raw.vcpus > 0 and cpu_time >= previous.cpu_time): + fraction = (cpu_time - previous.cpu_time) / (seconds * 1e9 * raw.vcpus) + # libvirt's total CPU time can include QEMU auxiliary threads, so + # a healthy sample can exceed the allotted vCPU time. The chart is + # defined as 0–100% of VM vCPU capacity. + cpu_percent = min(100.0, fraction * 100) + disk_same = same_run and bool(disk_signature) and disk_signature == previous.disk_signature + network_same = (same_run and bool(network_signature) + and network_signature == previous.network_signature) + point = { + "vm_id": vm_id, + "timestamp": timestamp, + "cpu_percent": cpu_percent, + "memory_used_mib": memory_used, + "memory_total_mib": memory_total, + "disk_read_bps": self._rate(disk["rd"], previous.disk["rd"] if previous else None, + seconds, disk_same), + "disk_write_bps": self._rate(disk["wr"], previous.disk["wr"] if previous else None, + seconds, disk_same), + "network_rx_bps": self._rate(network["rx"], previous.network["rx"] if previous else None, + seconds, network_same), + "network_tx_bps": self._rate(network["tx"], previous.network["tx"] if previous else None, + seconds, network_same), + } + self._previous[key] = _Baseline(monotonic, raw.generation, raw.vcpus, cpu_time, + disk_signature, disk, network_signature, network) + return point + + def forget_unseen(self, scope: str, seen: set[str]) -> None: + for key in list(self._previous): + if key[0] == scope and key[1] not in seen: + del self._previous[key] + + +class MetricsCollector: + """One daemon sampler owned by the single Uvicorn worker's lifespan.""" + + def __init__(self, store_getter: Callable[[], Any], + profile_getter: Callable[[], Mapping[str, Any] | None], + service_factory: Callable[[Mapping[str, Any]], Any], + *, interval_seconds: int = SAMPLE_INTERVAL_SECONDS) -> None: + self._store_getter = store_getter + self._profile_getter = profile_getter + self._service_factory = service_factory + self._interval_seconds = interval_seconds + self._sampler = MetricSampler() + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._prune_signal = threading.Event() + self._prune_thread: threading.Thread | None = None + + def sample_once(self, *, timestamp: int | None = None, + monotonic: float | None = None) -> None: + store = self._store_getter() + if store is None or not hasattr(store, "prune_metric_samples"): + return + timestamp = int(time.time()) if timestamp is None else timestamp + try: + profile = self._profile_getter() + if profile is None or profile.get("key_locked"): + return + scope = host_scope(profile) + rows = self._service_factory(profile).metric_counters() + monotonic = time.monotonic() if monotonic is None else monotonic + points = [self._sampler.observe(scope, row, timestamp=timestamp, + monotonic=monotonic) for row in rows] + self._sampler.forget_unseen(scope, {str(uuid.UUID(row.vm_id)) for row in rows}) + if points: + store.save_metric_samples(scope, points) + finally: + # Signal after sample/save (or a failed host access). The separate + # cleanup thread never delays the next libvirt measurement. + self._prune_signal.set() + + def _prune_loop(self) -> None: + while not self._stop.is_set(): + self._prune_signal.wait(timeout=self._interval_seconds) + self._prune_signal.clear() + if self._stop.is_set(): + break + store = self._store_getter() + if store is None or not hasattr(store, "prune_metric_samples"): + continue + while not self._stop.is_set(): + try: + removed = store.prune_metric_samples( + int(time.time()) - RETENTION_SECONDS) + except Exception as exc: + # Never echo database driver errors or connection details. + LOG.warning("VM metric retention cleanup failed: %s", + type(exc).__name__) + break + if not isinstance(removed, int) or removed < 5000: + break + # Sustain catch-up without occupying MariaDB continuously. + if self._stop.wait(0.1): + break + + def _run(self) -> None: + while not self._stop.is_set(): + started = time.monotonic() + try: + self.sample_once() + except Exception as exc: + # Never print libvirt/DB exception text: it can contain a URI, + # account name, or other connection details. + LOG.warning("VM metric collection failed: %s", type(exc).__name__) + self._stop.wait(max(0, self._interval_seconds - (time.monotonic() - started))) + + def start(self) -> None: + if self._thread is not None: + return + self._prune_thread = threading.Thread(target=self._prune_loop, daemon=True, + name="vm-metrics-retention") + self._prune_thread.start() + self._thread = threading.Thread(target=self._run, daemon=True, + name="vm-metrics-collector") + self._thread.start() + + def close(self) -> None: + self._stop.set() + self._prune_signal.set() + deadline = time.monotonic() + 15 + for worker in (self._thread, self._prune_thread): + if worker is not None: + worker.join(timeout=max(0, deadline - time.monotonic())) diff --git a/engine/virsh_panel/panel_state.py b/engine/virsh_panel/panel_state.py new file mode 100644 index 00000000..92bab3eb --- /dev/null +++ b/engine/virsh_panel/panel_state.py @@ -0,0 +1,186 @@ +"""Persistent, single-administrator setup state for the panel. + +The application creates a random one-time token on its first start. The web +setup route consumes it once, writing only a password hash to ``state.json``. +Both files are private to the account running the panel service. +""" + +from __future__ import annotations + +import fcntl +import hmac +import json +import os +import re +import secrets +import stat +import tempfile +import threading +from contextlib import contextmanager +from pathlib import Path + +from .auth import hash_password + + +_USERNAME = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{2,31}\Z") + + +class SetupError(Exception): + """A setup request cannot be completed.""" + + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +class PanelState: + def __init__(self, data_dir: Path) -> None: + supplied_dir = Path(data_dir) + if supplied_dir.is_symlink(): + raise ValueError("Panel data directory itself must not be a symlink") + # Resolve trusted parent paths while rejecting a symlink at the + # panel's own data directory. + self.data_dir = supplied_dir.resolve() + self.state_file = self.data_dir / "state.json" + self.token_file = self.data_dir / "setup-token" + self.lock_file = self.data_dir / ".setup.lock" + self._lock = threading.RLock() + self._ensure_directory() + + def _ensure_directory(self) -> None: + self.data_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + info = self.data_dir.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_mode & 0o077: + raise ValueError("Panel data directory must be a private directory (0700)") + + def _read(self) -> dict: + try: + info = self.state_file.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise ValueError("Panel state file must be private (0600)") + with self.state_file.open("r", encoding="utf-8") as stream: + state = json.load(stream) + except FileNotFoundError: + return {"version": 1} + if not isinstance(state, dict) or state.get("version") != 1: + raise ValueError("Panel state file is invalid") + return state + + def _read_token(self) -> str: + info = self.token_file.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise ValueError("Setup token file must be private (0600)") + token = self.token_file.read_text(encoding="ascii").strip() + if len(token) < 32: + raise ValueError("Setup token file is invalid") + return token + + @contextmanager + def _setup_lock(self): + """Serialize setup across workers/processes, not just Python threads.""" + with self._lock: + flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(self.lock_file, flags, 0o600) + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise ValueError("Panel setup lock must be private (0600)") + fcntl.flock(fd, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(fd, fcntl.LOCK_UN) + finally: + os.close(fd) + + def _fsync_directory(self) -> None: + directory_fd = os.open(self.data_dir, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + def _write(self, state: dict) -> None: + fd, temporary = tempfile.mkstemp(prefix=".state-", dir=self.data_dir) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(state, stream, ensure_ascii=False, separators=(",", ":")) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, self.state_file) + self._fsync_directory() + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + def admin(self) -> tuple[str, str] | None: + with self._lock: + admin = self._read().get("admin") + if admin is None: + return None + if ( + not isinstance(admin, dict) + or not isinstance(admin.get("username"), str) + or not isinstance(admin.get("password_hash"), str) + ): + raise ValueError("Panel administrator state is invalid") + return admin["username"], admin["password_hash"] + + def setup_required(self) -> bool: + return self.admin() is None + + def initialize_setup_token(self) -> str | None: + """Return the initial token, or ``None`` if an admin already exists. + + Restarting before setup returns the *same* token. It does not silently + rotate a secret that may already have been shown to the operator. + """ + with self._setup_lock(): + if not self.setup_required(): + # Recover from a crash after state.json was committed but + # before the now-obsolete token could be removed. + if self.token_file.exists(): + self.token_file.unlink() + self._fsync_directory() + return None + try: + return self._read_token() + except FileNotFoundError: + pass + token = secrets.token_urlsafe(32) + fd = os.open(self.token_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, "w", encoding="ascii") as stream: + stream.write(token + "\n") + stream.flush() + os.fsync(stream.fileno()) + self._fsync_directory() + except BaseException: + self.token_file.unlink(missing_ok=True) + raise + return token + + def create_admin(self, token: str, username: str, password: str) -> str: + if not _USERNAME.fullmatch(username): + raise SetupError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符") + if len(password) < 12 or len(password) > 1024: + raise SetupError("管理员密码长度须在 12 至 1024 位之间") + with self._setup_lock(): + if self.admin() is not None: + raise SetupError("管理员已创建", 409) + try: + expected = self._read_token() + except FileNotFoundError as exc: + raise SetupError("初始化口令不可用,请重新启动面板并查看启动终端输出", 503) from exc + if not hmac.compare_digest(token, expected): + raise SetupError("初始化口令无效", 403) + encoded = hash_password(password) + self._write({ + "version": 1, + "admin": {"username": username, "password_hash": encoded}, + }) + self.token_file.unlink(missing_ok=True) + self._fsync_directory() + return username diff --git a/engine/virsh_panel/remote_host.py b/engine/virsh_panel/remote_host.py new file mode 100644 index 00000000..875d26aa --- /dev/null +++ b/engine/virsh_panel/remote_host.py @@ -0,0 +1,825 @@ +"""Pin and manage one remote libvirt host without exposing its root SSH key. + +The panel runs under the local service account. Its OpenSSH user +configuration points at ``current/config``; ``current`` is an atomically +replaced symlink to a tested generation. Failed scans/tests never switch it. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import ipaddress +import json +import logging +import os +import re +import secrets +import shutil +import stat +import subprocess +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Mapping +from urllib.parse import quote + +from .ssh_agent import SSHAgentError, SSHAgentSession + + +SSH_ALIAS = "vp-managed" +LIBVIRT_URI = f"qemu+ssh://root@{SSH_ALIAS}/system?no_tty=1" +_DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") +_FINGERPRINT = re.compile(r"SHA256:[A-Za-z0-9+/]{43}\Z") +_KEY_HEADER = re.compile(r"-----BEGIN (?:OPENSSH |RSA |EC |DSA )?PRIVATE KEY-----\Z") +_GEN_NAME = re.compile(r"gen-[0-9a-f]{32}\Z") +_POOL_PATH = re.compile(r"/[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*\Z") +_BRIDGE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z") +_RUNNER = Callable[..., subprocess.CompletedProcess[str]] +LOG = logging.getLogger(__name__) + + +def _uri_for_generation(path: Path) -> str: + command = quote(str(path / "ssh-wrapper"), safe="/") + return f"{LIBVIRT_URI}&command={command}" + + +class RemoteHostError(Exception): + """A safe, user-facing connection/configuration error.""" + + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +@dataclass(frozen=True) +class HostProfile: + host: str + port: int + private_key: str = field(repr=False) + host_key: str = field(repr=False) + private_key_passphrase: str = field(default="", repr=False) + storage_pool: str = "default" + iso_pool: str = "iso" + rescue_iso_pool: str = "" + default_network: str = "default" + region: str = "" + public_pool_cidr: str = "" + public_gateway: str = "" + public_dns_servers: list[str] = field(default_factory=list) + public_reserved_ips: list[str] = field(default_factory=list) + public_vm_prefix: int | None = None + + +@dataclass +class StagedHost: + path: Path + metadata: dict[str, Any] + tested: bool = False + + @property + def ssh_config_file(self) -> str: + return str(self.path / "config") + + @property + def ssh_known_hosts_file(self) -> str: + return str(self.path / "known_hosts") + + @property + def ssh_target(self) -> str: + return SSH_ALIAS + + @property + def libvirt_uri(self) -> str: + # libvirt's ssh transport accepts ``command=`` as the executable to + # launch. The staged wrapper inserts -F so libvirt can be tested with + # the candidate config before the active ~/.ssh/config is switched. + return _uri_for_generation(self.path) + + +def _validate_host(host: str) -> str: + if not isinstance(host, str) or not host or len(host) > 253 or host != host.strip(): + raise RemoteHostError("宿主机地址格式无效") + try: + ipaddress.ip_address(host) + return host + except ValueError: + pass + if not all(_DNS_LABEL.fullmatch(label) for label in host.split(".")): + raise RemoteHostError("宿主机地址必须是 IP 或 DNS 名称") + return host.lower() + + +def _validate_port(port: int) -> int: + if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: + raise RemoteHostError("SSH 端口必须介于 1 到 65535") + return port + + +def _validate_name(value: str, label: str) -> str: + if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", value): + raise RemoteHostError(f"{label}名称格式无效") + if value.startswith("-") or value in {".", ".."}: + raise RemoteHostError(f"{label}名称格式无效") + return value + + +def _validate_pool_selector(value: str, label: str) -> str: + if isinstance(value, str) and value.startswith("/"): + if ( + len(value) <= 4096 + and _POOL_PATH.fullmatch(value) + and not any(part in {".", ".."} for part in value.split("/")) + ): + return value + raise RemoteHostError(f"{label}必须是规范的绝对目录路径") + return _validate_name(value, label) + + +def _validate_network_selector(value: str) -> str: + if isinstance(value, str) and value.startswith("bridge:"): + if not _BRIDGE_NAME.fullmatch(value.removeprefix("bridge:")): + raise RemoteHostError("网桥名称格式无效;请填写 bridge:br0,网桥名最长 15 字符") + return value + return _validate_name(value, "网络") + + +def _validate_region(value: str) -> str: + # This is an operator-supplied display label, not a provider region ID. + if (not isinstance(value, str) or len(value) > 64 or value != value.strip() + or any(ord(char) < 32 or ord(char) == 127 for char in value)): + raise RemoteHostError("宿主机地区最多 64 字符,且不能包含控制字符或首尾空格") + return value + + +def validate_public_pool( + public_pool_cidr: str, + public_gateway: str, + public_dns_servers: list[str], + public_reserved_ips: list[str], + host: str, + public_vm_prefix: int | None = None, +) -> dict[str, Any]: + """Validate one host's public IPv4 pool without probing live network use. + + The SSH host address is deliberately not persisted in the reserved list: + the allocator excludes a literal host IPv4 address while allocating, so + the operator can still distinguish explicit reservations from that rule. + A VM prefix override changes guest network configuration, never the set + of addresses this pool may allocate. + """ + if not isinstance(public_pool_cidr, str) or not isinstance(public_gateway, str): + raise RemoteHostError("公网地址池和网关格式无效") + if (not isinstance(public_dns_servers, (list, tuple)) + or not isinstance(public_reserved_ips, (list, tuple))): + raise RemoteHostError("公网 DNS 和保留 IP 必须是地址列表") + cidr = public_pool_cidr.strip() + gateway = public_gateway.strip() + dns_input = list(public_dns_servers) + reserved_input = list(public_reserved_ips) + if not any((cidr, gateway, dns_input, reserved_input)): + if public_vm_prefix is not None: + raise RemoteHostError("启用虚拟机网卡前缀前必须配置公网地址池") + return { + "public_pool_cidr": "", + "public_gateway": "", + "public_dns_servers": [], + "public_reserved_ips": [], + "public_vm_prefix": None, + } + if not cidr or not gateway or not dns_input: + raise RemoteHostError("启用公网地址池时必须同时填写公网网段、网关和 DNS") + if len(reserved_input) > 254: + raise RemoteHostError("保留 IP 最多可填写 254 个地址") + try: + # Providers sometimes describe a routed block using its gateway (for + # example 123.123.123.113/28). Normalize that host/CIDR to its actual + # network before checking membership or allocating any addresses. + network = ipaddress.IPv4Network(cidr, strict=False) + except (ValueError, ipaddress.AddressValueError, ipaddress.NetmaskValueError) as exc: + raise RemoteHostError("公网地址池必须填写有效的 IPv4 地址/前缀") from exc + if (not 24 <= network.prefixlen <= 30 + or not network.network_address.is_global + or not network.broadcast_address.is_global): + raise RemoteHostError("公网地址池必须是可路由的 IPv4 网段,前缀长度为 /24 至 /30") + if network.prefixlen == 24 and cidr.split("/", 1)[0] != str(network.network_address): + raise RemoteHostError("/24 地址池必须填写网段起始地址;如果实际只获配 /28,请填写 /28 而不是 /24") + if (public_vm_prefix is not None + and (isinstance(public_vm_prefix, bool) + or not isinstance(public_vm_prefix, int) + or not 24 <= public_vm_prefix <= network.prefixlen)): + raise RemoteHostError("虚拟机网卡前缀须介于 /24 和地址池前缀之间") + + def parse_ipv4(value: str, label: str) -> ipaddress.IPv4Address: + if not isinstance(value, str) or not value or value != value.strip(): + raise RemoteHostError(f"{label}必须是 IPv4 地址") + try: + return ipaddress.IPv4Address(value) + except (ValueError, ipaddress.AddressValueError) as exc: + raise RemoteHostError(f"{label}必须是 IPv4 地址") from exc + + gateway_ip = parse_ipv4(gateway, "公网网关") + if gateway_ip not in network or gateway_ip in ( + network.network_address, network.broadcast_address): + raise RemoteHostError("公网网关必须位于所配置的网段内") + + def unique_ips(values: list[str], label: str, *, in_pool: bool) -> list[str]: + normalized: list[str] = [] + seen: set[str] = set() + for value in values: + address = parse_ipv4(value, label) + if in_pool: + if address not in network or address in ( + network.network_address, network.broadcast_address): + raise RemoteHostError(f"{label}必须位于所配置的网段内") + elif not address.is_global: + raise RemoteHostError(f"{label}必须是可路由的公网 IPv4 地址") + address_text = str(address) + if address_text not in seen: + seen.add(address_text) + normalized.append(address_text) + return normalized + + dns = unique_ips(dns_input, "公网 DNS", in_pool=False) + reserved = unique_ips(reserved_input, "保留 IP", in_pool=True) + if len(dns) > 4: + raise RemoteHostError("公网 DNS 最多可填写 4 个地址") + if not dns: + raise RemoteHostError("启用公网地址池时必须填写 DNS") + return { + "public_pool_cidr": str(network), + "public_gateway": str(gateway_ip), + "public_dns_servers": dns, + "public_reserved_ips": reserved, + "public_vm_prefix": public_vm_prefix, + } + + +def _key_parts(line: str) -> tuple[str, str]: + if not isinstance(line, str) or len(line) > 4096 or any(c in line for c in "\r\n\x00"): + raise RemoteHostError("主机公钥格式无效") + fields = line.split() + if len(fields) == 2 and fields[0] == "ssh-ed25519": + key_type, encoded = fields + elif len(fields) == 3 and fields[1] == "ssh-ed25519": + key_type, encoded = fields[1:] + else: + raise RemoteHostError("目前只支持 Ed25519 SSH 主机公钥") + try: + blob = base64.b64decode(encoded, validate=True) + except (ValueError, binascii.Error) as exc: + raise RemoteHostError("主机公钥内容无效") from exc + if ( + len(blob) != 51 + or blob[:4] != b"\x00\x00\x00\x0b" + or blob[4:15] != b"ssh-ed25519" + or blob[15:19] != b"\x00\x00\x00\x20" + ): + raise RemoteHostError("主机公钥内容无效") + return key_type, base64.b64encode(blob).decode("ascii") + + +def _fingerprint(key: str) -> str: + _key_type, encoded = _key_parts(key) + digest = hashlib.sha256(base64.b64decode(encoded)).digest() + return "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("=") + + +def _validate_private_key(value: str) -> bytes: + if not isinstance(value, str) or not 0 < len(value) <= 131072: + raise RemoteHostError("请提供现有 SSH 私钥,最大 128 KiB") + value = value.replace("\r\n", "\n") + if "\x00" in value or "\r" in value: + raise RemoteHostError("SSH 私钥格式无效") + header = value.split("\n", 1)[0] + if not _KEY_HEADER.fullmatch(header) or "-----END " not in value: + raise RemoteHostError("请提供 PEM 或 OpenSSH 格式的私钥") + return (value.rstrip("\n") + "\n").encode("ascii", errors="strict") + + +def _write_private(path: Path, content: bytes) -> None: + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + descriptor = os.open(path, flags, 0o600) + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + except BaseException: + path.unlink(missing_ok=True) + raise + + +def _quoted_path(path: Path) -> str: + value = str(path) + if any(c in value for c in "\r\n\x00"): + raise RemoteHostError("面板数据路径包含不支持的字符") + return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +class RemoteHostManager: + """Prepare, test, and atomically select a root-key SSH generation.""" + + def __init__( + self, + data_dir: Path, + *, + ssh_user_config_path: Path | None = None, + ssh_binary: str = "ssh", + keyscan_binary: str = "ssh-keyscan", + keygen_binary: str = "ssh-keygen", + runner: _RUNNER | None = None, + agent_factory: Callable[[Path, Path, str], SSHAgentSession] = SSHAgentSession, + ) -> None: + # Canonicalize once so staged paths, the active target and cleanup + # comparisons all use the same path. The final data directory itself + # must not be a symlink; a trusted parent may be one. + requested_data_dir = Path(data_dir).expanduser().absolute() + if requested_data_dir.is_symlink(): + raise RemoteHostError("面板数据目录不能是符号链接", status=500) + self.data_dir = requested_data_dir.resolve(strict=False) + self.ssh_user_config_path = ( + Path(ssh_user_config_path).expanduser().absolute() + if ssh_user_config_path is not None + else self.data_dir / ".ssh" / "config" + ) + self.ssh_binary = ssh_binary + self.keyscan_binary = keyscan_binary + self.keygen_binary = keygen_binary + self._run = runner or subprocess.run + self._agent_factory = agent_factory + self._lock = threading.RLock() + self._pending: set[Path] = set() + self._agents: dict[Path, SSHAgentSession] = {} + self.cleanup_inactive() + self._schedule_cleanup() + + @property + def libvirt_uri(self) -> str: + generation = self._current_generation() + return _uri_for_generation(generation) if generation is not None else LIBVIRT_URI + + def _exec(self, argv: list[str], *, timeout: float) -> subprocess.CompletedProcess[str]: + try: + return self._run( + argv, + check=False, + capture_output=True, + text=True, + timeout=timeout, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise RemoteHostError("SSH 命令超时或无法启动", status=502) from exc + + def scan(self, host: str, port: int) -> dict[str, Any]: + """Scan but do not trust the public key; the operator must verify it.""" + host = _validate_host(host) + port = _validate_port(port) + result = self._exec( + [self.keyscan_binary, "-T", "8", "-p", str(port), "-t", "ed25519", host], + timeout=12, + ) + found: set[str] = set() + for line in result.stdout.splitlines(): + if not line or line.startswith("#"): + continue + try: + key_type, encoded = _key_parts(line) + except RemoteHostError: + continue + found.add(f"{key_type} {encoded}") + if result.returncode != 0 or len(found) != 1: + raise RemoteHostError("无法获取唯一的 Ed25519 主机公钥,请检查地址和端口", status=502) + host_key = found.pop() + return { + "host": host, + "port": port, + "key_type": "ssh-ed25519", + "fingerprint": _fingerprint(host_key), + "host_key": host_key, + "known_hosts_line": f"{SSH_ALIAS} {host_key}", + } + + def _ensure_storage(self) -> None: + self.data_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + if self.data_dir.is_symlink(): + raise RemoteHostError("面板数据目录不能是符号链接") + self.data_dir.chmod(0o700) + generations = self.data_dir / "generations" + generations.mkdir(mode=0o700, exist_ok=True) + if generations.is_symlink(): + raise RemoteHostError("面板配置目录不能是符号链接") + generations.chmod(0o700) + + def stage( + self, + profile: HostProfile | Mapping[str, Any], + confirmed_fingerprint: str, + ) -> StagedHost: + """Re-scan and write an inactive generation after explicit verification.""" + if isinstance(profile, Mapping): + try: + profile = HostProfile(**profile) + except (TypeError, ValueError) as exc: + raise RemoteHostError("宿主机配置字段无效") from exc + if not isinstance(profile, HostProfile): + raise RemoteHostError("宿主机配置字段无效") + host = _validate_host(profile.host) + port = _validate_port(profile.port) + storage_pool = _validate_pool_selector(profile.storage_pool, "磁盘池") + iso_pool = _validate_pool_selector(profile.iso_pool, "ISO 池") + rescue_iso_pool = ( + _validate_pool_selector(profile.rescue_iso_pool, "救援 ISO 池") + if profile.rescue_iso_pool != "" else "" + ) + if rescue_iso_pool and rescue_iso_pool == iso_pool: + raise RemoteHostError("救援 ISO 池不能与安装 ISO 池相同") + default_network = _validate_network_selector(profile.default_network) + region = _validate_region(profile.region) + public_pool = validate_public_pool( + profile.public_pool_cidr, + profile.public_gateway, + profile.public_dns_servers, + profile.public_reserved_ips, + host, + profile.public_vm_prefix, + ) + if not isinstance(confirmed_fingerprint, str) or not _FINGERPRINT.fullmatch(confirmed_fingerprint): + raise RemoteHostError("请确认扫描得到的 SHA256 主机指纹") + try: + submitted_type, submitted_encoded = _key_parts(profile.host_key) + except RemoteHostError as exc: + raise RemoteHostError("提交的主机公钥格式无效") from exc + submitted_key = f"{submitted_type} {submitted_encoded}" + scanned = self.scan(host, port) + if scanned["host_key"] != submitted_key or scanned["fingerprint"] != confirmed_fingerprint: + raise RemoteHostError("主机公钥或指纹在扫描后发生变化,请重新核验", status=409) + + self._ensure_storage() + generation = self.data_dir / "generations" / ("gen-" + secrets.token_hex(16)) + generation.mkdir(mode=0o700) + try: + key_path = generation / "id_private" + if profile.private_key: + try: + key_bytes = _validate_private_key(profile.private_key) + except UnicodeEncodeError: + raise RemoteHostError("SSH 私钥必须是 ASCII PEM 文本") from None + else: + current = self._current_generation() + if current is None: + raise RemoteHostError("首次连接必须提供现有 SSH 私钥") + try: + key_bytes = (current / "id_private").read_bytes() + except OSError as exc: + raise RemoteHostError("已保存的 SSH 私钥无法读取", status=500) from exc + _write_private(key_path, key_bytes) + key_check = self._exec( + [self.keygen_binary, "-y", "-P", "", "-f", str(key_path)], + timeout=8, + ) + # Successful ssh-keygen -y is authoritative here: unencrypted + # ECDSA keys produce an `ecdsa-sha2-*` public key, not `ssh-*`. + encrypted = key_check.returncode != 0 or len(key_check.stdout.split()) < 2 + identity_path = key_path + identity_agent = "none" + if encrypted: + if not profile.private_key_passphrase: + raise RemoteHostError("私钥已加密或无效;请填写私钥口令后重试") + try: + agent = self._agent_factory(generation, key_path, profile.private_key_passphrase) + except SSHAgentError as exc: + raise RemoteHostError("私钥口令错误或私钥无效,无法解锁", 400) from exc + with self._lock: + self._agents[generation] = agent + identity_path = generation / "identity.pub" + _write_private(identity_path, (agent.public_key + "\n").encode("ascii")) + identity_agent = _quoted_path(agent.socket_path) + + known_hosts = generation / "known_hosts" + _write_private(known_hosts, f"{SSH_ALIAS} {submitted_key}\n".encode("ascii")) + ssh_config = generation / "config" + config_text = ( + f"Host {SSH_ALIAS}\n" + f" HostName {host}\n" + f" Port {port}\n" + " User root\n" + f" IdentityFile {_quoted_path(identity_path)}\n" + f" UserKnownHostsFile {_quoted_path(known_hosts)}\n" + " GlobalKnownHostsFile /dev/null\n" + f" HostKeyAlias {SSH_ALIAS}\n" + " HostKeyAlgorithms ssh-ed25519\n" + " StrictHostKeyChecking yes\n" + " VerifyHostKeyDNS no\n" + " BatchMode yes\n" + " IdentitiesOnly yes\n" + f" IdentityAgent {identity_agent}\n" + " PreferredAuthentications publickey\n" + " PasswordAuthentication no\n" + " KbdInteractiveAuthentication no\n" + " GSSAPIAuthentication no\n" + " ForwardAgent no\n" + " ProxyCommand none\n" + " ProxyJump none\n" + " CanonicalizeHostname no\n" + " ControlMaster no\n" + " ControlPath none\n" + " UpdateHostKeys no\n" + " RequestTTY no\n" + " ServerAliveInterval 15\n" + " ServerAliveCountMax 2\n" + " ConnectTimeout 10\n" + ) + _write_private(ssh_config, config_text.encode("ascii")) + wrapper = generation / "ssh-wrapper" + wrapper_text = ( + "#!/usr/bin/env python3\n" + "import os\n" + "import sys\n" + f"os.execvp({self.ssh_binary!r}, " + f"[{self.ssh_binary!r}, '-F', {str(ssh_config)!r}, *sys.argv[1:]])\n" + ) + _write_private(wrapper, wrapper_text.encode("ascii")) + wrapper.chmod(0o700) + metadata = { + "host": host, + "port": port, + "key_type": "ssh-ed25519", + "fingerprint": confirmed_fingerprint, + "private_key_configured": True, + "private_key_encrypted": encrypted, + "storage_pool": storage_pool, + "iso_pool": iso_pool, + "rescue_iso_pool": rescue_iso_pool, + "default_network": default_network, + "region": region, + **public_pool, + } + _write_private( + generation / "profile.json", + json.dumps(metadata, ensure_ascii=False).encode("utf-8"), + ) + with self._lock: + self._pending.add(generation) + return StagedHost(generation, metadata) + except BaseException: + with self._lock: + agent = self._agents.pop(generation, None) + if agent is not None: + agent.close() + shutil.rmtree(generation) + raise + + def test(self, staged: StagedHost) -> dict[str, Any]: + """Check the staged key, pinned host key, SSH, and remote libvirt.""" + self._check_staged(staged) + result = self._exec( + [ + self.ssh_binary, + "-F", + staged.ssh_config_file, + "-T", + "-o", + "ConnectTimeout=10", + SSH_ALIAS, + "/usr/bin/virsh -c qemu:///system list --all", + ], + timeout=22, + ) + if result.returncode != 0: + # Do not reflect stderr: SSH diagnostics can contain arbitrary + # remote data or paths, and never need to include the secret key. + raise RemoteHostError( + "SSH 或宿主机 libvirt 连接失败;请检查 root 密钥、端口、主机指纹和 virsh 服务", + status=502, + ) + staged.tested = True + return {"ok": True, "ssh": "connected", "libvirt": "available"} + + def _check_staged(self, staged: StagedHost) -> None: + if not isinstance(staged, StagedHost) or staged.path.parent != self.data_dir / "generations": + raise RemoteHostError("暂存配置无效") + if staged.path.is_symlink() or not staged.path.is_dir(): + raise RemoteHostError("暂存配置不存在") + + def _current_generation(self) -> Path | None: + current = self.data_dir / "current" + if not current.is_symlink(): + if current.exists(): + raise RemoteHostError("已保存的宿主机配置损坏", status=500) + return None + target = current.resolve() + if target.parent != self.data_dir / "generations" or not target.is_dir(): + raise RemoteHostError("已保存的宿主机配置损坏", status=500) + return target + + def _ensure_user_ssh_config(self) -> None: + ssh_dir = self.ssh_user_config_path.parent + ssh_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + if ssh_dir.is_symlink(): + raise RemoteHostError("服务账号 SSH 目录不能是符号链接", status=500) + ssh_dir.chmod(0o700) + destination = self.data_dir / "current" / "config" + user_config = self.ssh_user_config_path + if user_config.is_symlink(): + if user_config.readlink() != destination: + raise RemoteHostError("服务账号已有其他 SSH 配置,请勿覆盖", status=409) + elif user_config.exists(): + raise RemoteHostError("服务账号已有其他 SSH 配置,请勿覆盖", status=409) + else: + user_config.symlink_to(destination) + + def commit(self, staged: StagedHost) -> dict[str, Any]: + """Activate a previously tested generation with one atomic symlink swap.""" + with self._lock: + self._check_staged(staged) + if not staged.tested: + raise RemoteHostError("保存前必须先测试宿主机连接", status=409) + self._ensure_user_ssh_config() + previous = self._current_generation() + link = self.data_dir / (".current-" + secrets.token_hex(8)) + link.symlink_to(staged.path) + try: + os.replace(link, self.data_dir / "current") + finally: + link.unlink(missing_ok=True) + self._pending.discard(staged.path) + if previous is not None and previous != staged.path: + # Give in-flight API calls that obtained the old URI time to + # launch SSH before removing that generation's private key. + try: + os.utime(previous, None) + except OSError as exc: + LOG.warning("could not date retired SSH generation: %s", exc) + self._schedule_cleanup() + return self.current() or {} + + def abort(self, staged: StagedHost) -> None: + with self._lock: + self._check_staged(staged) + if self._current_generation() == staged.path: + raise RemoteHostError("不能删除正在使用的宿主机配置", status=409) + self._pending.discard(staged.path) + agent = self._agents.pop(staged.path, None) + if agent is not None: + agent.close() + shutil.rmtree(staged.path) + + def _schedule_cleanup(self) -> None: + timer = threading.Timer(65, self.cleanup_inactive) + timer.daemon = True + timer.start() + + def cleanup_inactive(self, *, grace_seconds: float = 60) -> int: + """Remove only retired generations owned by this manager's data tree.""" + if grace_seconds < 0: + raise ValueError("grace_seconds must not be negative") + with self._lock: + root = self.data_dir / "generations" + if root.is_symlink(): + raise RemoteHostError("面板配置目录损坏", status=500) + if not root.exists(): + return 0 + if not root.is_dir(): + raise RemoteHostError("面板配置目录损坏", status=500) + active = self._current_generation() + now = time.time() + removed = 0 + for entry in root.iterdir(): + if ( + not _GEN_NAME.fullmatch(entry.name) + or entry.is_symlink() + or not entry.is_dir() + or entry == active + or entry in self._pending + ): + continue + try: + if now - entry.stat().st_mtime < grace_seconds: + continue + agent = self._agents.pop(entry, None) + if agent is not None: + agent.close() + shutil.rmtree(entry) + removed += 1 + except OSError as exc: + LOG.warning("could not prune retired SSH generation: %s", exc) + return removed + + def unlock_current(self, passphrase: str) -> dict[str, Any]: + """Load the saved encrypted key into a process-local SSH agent.""" + with self._lock: + generation = self._current_generation() + if generation is None: + raise RemoteHostError("请先配置宿主机", 409) + profile = self.current() + if profile is None or not profile["private_key_encrypted"]: + raise RemoteHostError("当前 SSH 私钥不需要解锁", 409) + if not profile["key_locked"]: + return profile + try: + agent = self._agent_factory(generation, generation / "id_private", passphrase) + except SSHAgentError as exc: + raise RemoteHostError("私钥口令错误或私钥无效,无法解锁", 400) from exc + try: + expected = (generation / "identity.pub").read_text(encoding="ascii").split() + actual = agent.public_key.split() + if len(expected) < 2 or actual[:2] != expected[:2]: + raise RemoteHostError("已保存的私钥与公钥不匹配", 500) + self._set_agent_socket(generation, agent.socket_path) + except BaseException: + agent.close() + raise + previous = self._agents.pop(generation, None) + if previous is not None: + previous.close() + self._agents[generation] = agent + return self.current() or {} + + @staticmethod + def _set_agent_socket(generation: Path, socket_path: Path) -> None: + """Atomically point the active SSH config at the newly unlocked agent.""" + config = generation / "config" + info = config.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise RemoteHostError("已保存的 SSH 配置权限无效", 500) + lines = config.read_text(encoding="ascii").splitlines(keepends=True) + replacements = [index for index, line in enumerate(lines) + if line.startswith(" IdentityAgent ")] + if len(replacements) != 1: + raise RemoteHostError("已保存的 SSH 配置损坏", 500) + lines[replacements[0]] = f" IdentityAgent {_quoted_path(socket_path)}\n" + temporary = generation / (".config-" + secrets.token_hex(8)) + try: + _write_private(temporary, "".join(lines).encode("ascii")) + os.replace(temporary, config) + finally: + temporary.unlink(missing_ok=True) + + def close(self) -> None: + """Stop all process-local agents on graceful panel shutdown.""" + with self._lock: + agents = list(self._agents.values()) + self._agents.clear() + for agent in agents: + agent.close() + + def current(self) -> dict[str, Any] | None: + generation = self._current_generation() + if generation is None: + return None + try: + metadata = json.loads((generation / "profile.json").read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise RemoteHostError("已保存的宿主机配置损坏", status=500) from exc + fields = ( + "host", + "port", + "key_type", + "fingerprint", + "private_key_configured", + "storage_pool", + "iso_pool", + "default_network", + ) + if any(field not in metadata for field in fields): + raise RemoteHostError("已保存的宿主机配置损坏", status=500) + try: + region = _validate_region(metadata.get("region", "")) + rescue_iso_pool = metadata.get("rescue_iso_pool", "") + if rescue_iso_pool != "": + rescue_iso_pool = _validate_pool_selector(rescue_iso_pool, "救援 ISO 池") + if rescue_iso_pool == metadata["iso_pool"]: + raise RemoteHostError("救援 ISO 池不能与安装 ISO 池相同") + public_pool = validate_public_pool( + metadata.get("public_pool_cidr", ""), + metadata.get("public_gateway", ""), + metadata.get("public_dns_servers", []), + metadata.get("public_reserved_ips", []), + metadata["host"], + metadata.get("public_vm_prefix"), + ) + except RemoteHostError as exc: + raise RemoteHostError("已保存的宿主机配置损坏", status=500) from exc + return { + **{field: metadata[field] for field in fields}, + "rescue_iso_pool": rescue_iso_pool, + "region": region, + **public_pool, + "private_key_encrypted": bool(metadata.get("private_key_encrypted", False)), + "key_locked": bool(metadata.get("private_key_encrypted", False)) and not ( + generation in self._agents and self._agents[generation].alive + ), + "libvirt_uri": _uri_for_generation(generation), + "ssh_target": SSH_ALIAS, + "ssh_config_file": str(generation / "config"), + "ssh_known_hosts_file": str(generation / "known_hosts"), + } + + +# A clearer name for callers that prefer "store" terminology. +RemoteHostStore = RemoteHostManager diff --git a/engine/virsh_panel/rescue_templates.py b/engine/virsh_panel/rescue_templates.py new file mode 100644 index 00000000..08168119 --- /dev/null +++ b/engine/virsh_panel/rescue_templates.py @@ -0,0 +1,151 @@ +"""Host-scoped catalog for administrator-uploaded rescue ISO images. + +The ISO bytes live in the remote libvirt rescue ISO pool. In production only the +catalog metadata is stored here, encrypted by the MariaDB record store. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import threading +from pathlib import Path +from typing import Any, Mapping + +from .cloud_templates import TemplateError, validate_template_name + + +RESCUE_ID_RE = re.compile(r"[0-9a-f]{32}\Z") +RESCUE_VOLUME_RE = re.compile(r"panel-rescue-[0-9a-f]{32}\.iso\Z") +MAX_RESCUE_ISO_BYTES = 8 * 1024**3 + + +def rescue_scope(profile: Mapping[str, Any]) -> str: + """Bind records to a verified SSH host and its selected rescue pool.""" + if profile.get("host_id"): + pool = profile.get("rescue_iso_pool") + if not pool: + raise TemplateError("请先在宿主机设置中配置独立的救援 ISO 目录", 409) + raw = json.dumps(["virt-cloud", profile["host_id"], pool]) + return hashlib.sha256(raw.encode("ascii")).hexdigest() + try: + identity = [profile[key] for key in ( + "host", "port", "fingerprint", "rescue_iso_pool")] + except (KeyError, TypeError) as exc: + raise TemplateError("宿主机资料不完整,无法选择救援模版", 409) from exc + if (not isinstance(identity[0], str) or isinstance(identity[1], bool) + or not isinstance(identity[1], int) + or not isinstance(identity[2], str) or not isinstance(identity[3], str)): + raise TemplateError("宿主机资料不完整,无法选择救援模版", 409) + if not identity[3]: + raise TemplateError("请先在宿主机设置中配置独立的救援 ISO 目录", 409) + raw = json.dumps(identity, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +def rescue_volume_name(template_id: str) -> str: + if not isinstance(template_id, str) or not RESCUE_ID_RE.fullmatch(template_id): + raise TemplateError("救援模版标识无效") + return f"panel-rescue-{template_id}.iso" + + +def verify_bootable_iso(path: Path) -> None: + """Reject ordinary data ISOs, including cloud-init seed images. + + El Torito boot records are required for x86 BIOS/UEFI optical boot. This + checks the disc descriptor, not that its bundled operating system works. + """ + size = path.stat().st_size + if not 1024 * 1024 <= size <= MAX_RESCUE_ISO_BYTES: + raise TemplateError("救援 ISO 大小必须在 1 MiB 至 8 GiB 之间", 413) + bootable = False + with path.open("rb") as image: + for sector in range(16, 80): + image.seek(sector * 2048) + descriptor = image.read(2048) + if len(descriptor) != 2048 or descriptor[1:6] != b"CD001": + raise TemplateError("上传文件不是有效的 ISO 9660 镜像", 422) + if (descriptor[0] == 0 + and descriptor[7:30].rstrip(b" ") == b"EL TORITO SPECIFICATION" + and int.from_bytes(descriptor[71:75], "little") > 0): + bootable = True + if descriptor[0] == 255: + break + if not bootable: + raise TemplateError("ISO 未包含可识别的 El Torito 启动记录,无法用作救援模版", 422) + + +class RescueTemplateStore: + """Small catalog with the same API in production and isolated HTTP tests.""" + + def __init__(self, store: Any | None) -> None: + self.store = store + self._memory: dict[str, str] = {} + self._lock = threading.RLock() + + def _list(self, scope: str) -> list[dict[str, Any]]: + source = (self.store.list("rescue_template") if self.store is not None + else self._memory.copy()) + records = [] + for key, payload in source.items(): + if not key.startswith(f"{scope}:"): + continue + try: + record = json.loads(payload) + except (TypeError, ValueError) as exc: + raise TemplateError("救援模版数据库记录损坏", 500) from exc + if (not isinstance(record, dict) + or not RESCUE_ID_RE.fullmatch(str(record.get("id", ""))) + or record.get("volume_name") != rescue_volume_name(record["id"]) + or not isinstance(record.get("name"), str) + or not isinstance(record.get("size_bytes"), int)): + raise TemplateError("救援模版数据库记录损坏", 500) + records.append(record) + return sorted(records, key=lambda item: item["name"].casefold()) + + def list(self, scope: str) -> list[dict[str, Any]]: + with self._lock: + return self._list(scope) + + def get(self, scope: str, template_id: str) -> dict[str, Any]: + rescue_volume_name(template_id) + with self._lock: + for record in self._list(scope): + if record["id"] == template_id: + return record + raise TemplateError("救援模版不存在或不属于当前宿主机", 404) + + def add(self, scope: str, record: dict[str, Any]) -> dict[str, Any]: + template_id = record.get("id") + if record.get("volume_name") != rescue_volume_name(template_id): + raise TemplateError("救援模版记录无效") + name = validate_template_name(record.get("name")) + if (isinstance(record.get("size_bytes"), bool) + or not isinstance(record.get("size_bytes"), int) + or not 0 < record["size_bytes"] <= MAX_RESCUE_ISO_BYTES): + raise TemplateError("救援 ISO 大小无效") + record = {**record, "name": name} + key = f"{scope}:{template_id}" + value = json.dumps(record, ensure_ascii=False, separators=(",", ":")) + with self._lock: + existing = self._list(scope) + if any(row["id"] == template_id for row in existing): + raise TemplateError("此救援模版已存在", 409) + if any(row["name"].casefold() == name.casefold() for row in existing): + raise TemplateError("当前宿主机已有同名救援模版", 409) + if self.store is not None: + if not self.store.insert("rescue_template", key, value): + raise TemplateError("此救援模版已存在", 409) + else: + self._memory[key] = value + return record + + def delete(self, scope: str, template_id: str) -> None: + self.get(scope, template_id) + key = f"{scope}:{template_id}" + with self._lock: + if self.store is not None: + self.store.delete("rescue_template", key) + else: + self._memory.pop(key, None) diff --git a/engine/virsh_panel/smtp_service.py b/engine/virsh_panel/smtp_service.py new file mode 100644 index 00000000..d5f74178 --- /dev/null +++ b/engine/virsh_panel/smtp_service.py @@ -0,0 +1,215 @@ +"""Validated SMTP settings and registration verification mail delivery. + +The settings store deliberately uses the panel's encrypted record store. The +module never logs SMTP server responses because those can contain addresses or +authentication details supplied by a remote server. +""" + +from __future__ import annotations + +import ipaddress +import json +import re +import smtplib +import ssl +from dataclasses import dataclass, field +from email.message import EmailMessage +from typing import Any, Mapping, Protocol + + +_DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") +_LOCAL_PART = re.compile(r"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*\Z") +_SIX_DIGITS = re.compile(r"[0-9]{6}\Z") +_SMTP_RECORD_TYPE = "smtp" +_SMTP_RECORD_KEY = "current" + + +class SMTPError(Exception): + """Safe user-facing SMTP configuration or delivery failure.""" + + def __init__(self, message: str, status: int = 422) -> None: + super().__init__(message) + self.status = status + + +def _validate_host(host: str) -> str: + if (not isinstance(host, str) or not host or len(host) > 253 + or host != host.strip()): + raise SMTPError("SMTP 服务器地址格式无效") + try: + ipaddress.ip_address(host) + return host + except ValueError: + pass + if not all(_DNS_LABEL.fullmatch(label) for label in host.split(".")): + raise SMTPError("SMTP 服务器地址必须是 IP 或 DNS 名称") + return host.lower() + + +def validate_email(address: str) -> str: + """Accept a bare ASCII mailbox address, never a display name or header.""" + + if (not isinstance(address, str) or len(address) > 254 + or address != address.strip() or address.count("@") != 1): + raise SMTPError("邮箱地址格式无效") + local, domain = address.rsplit("@", 1) + if (not local or len(local) > 64 or not _LOCAL_PART.fullmatch(local) + or not domain or len(domain) > 253 + or not all(_DNS_LABEL.fullmatch(label) for label in domain.split("."))): + raise SMTPError("邮箱地址格式无效") + return f"{local}@{domain.lower()}" + + +@dataclass(frozen=True) +class SMTPConfig: + host: str + port: int + tls_mode: str + from_address: str + username: str = "" + password: str = field(default="", repr=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "host", _validate_host(self.host)) + if (isinstance(self.port, bool) or not isinstance(self.port, int) + or not 1 <= self.port <= 65535): + raise SMTPError("SMTP 端口必须介于 1 到 65535") + if (not isinstance(self.tls_mode, str) + or self.tls_mode not in {"ssl", "starttls", "none"}): + raise SMTPError("SMTP 加密方式无效") + object.__setattr__(self, "from_address", validate_email(self.from_address)) + if (not isinstance(self.username, str) or len(self.username) > 256 + or self.username != self.username.strip() + or any(ord(char) < 32 or ord(char) == 127 for char in self.username)): + raise SMTPError("SMTP 用户名格式无效") + if not isinstance(self.password, str) or len(self.password) > 2048: + raise SMTPError("SMTP 密码格式无效") + if bool(self.username) != bool(self.password): + raise SMTPError("SMTP 用户名和密码必须同时填写") + if self.username and self.tls_mode == "none": + raise SMTPError("SMTP 账号认证必须启用 SSL 或 STARTTLS") + + @classmethod + def from_mapping(cls, values: Mapping[str, Any]) -> SMTPConfig: + if not isinstance(values, Mapping): + raise SMTPError("SMTP 配置格式无效") + return cls( + host=values.get("host"), + port=values.get("port"), + tls_mode=values.get("tls_mode"), + from_address=values.get("from_address"), + username=values.get("username", ""), + password=values.get("password", ""), + ) + + def as_record(self) -> dict[str, str | int]: + """Full value for the *encrypted* database record only.""" + + return { + "host": self.host, + "port": self.port, + "tls_mode": self.tls_mode, + "from_address": self.from_address, + "username": self.username, + "password": self.password, + } + + def public_status(self) -> dict[str, str | int | bool]: + """Admin-only status; intentionally never includes the SMTP password.""" + + return { + "configured": True, + "host": self.host, + "port": self.port, + "tls_mode": self.tls_mode, + "from_address": self.from_address, + "username": self.username, + "password_configured": bool(self.password), + } + + +class _RecordStore(Protocol): + def get(self, record_type: str, record_key: str) -> str | None: ... + def set(self, record_type: str, record_key: str, value: str) -> None: ... + + +class SMTPSettingsStore: + """One SMTP configuration in the panel's AES-GCM-encrypted record table.""" + + def __init__(self, records: _RecordStore) -> None: + self._records = records + + def get(self) -> SMTPConfig | None: + raw = self._records.get(_SMTP_RECORD_TYPE, _SMTP_RECORD_KEY) + if raw is None: + return None + try: + payload = json.loads(raw) + return SMTPConfig.from_mapping(payload) + except (ValueError, TypeError, SMTPError): + raise SMTPError("已保存的 SMTP 配置无效,请重新保存", status=503) from None + + def save(self, values: Mapping[str, Any]) -> SMTPConfig: + if not isinstance(values, Mapping): + raise SMTPError("SMTP 配置格式无效") + candidate = dict(values) + if candidate.get("password") in (None, ""): + current = self.get() + if current is not None and candidate.get("username", "") == current.username: + candidate["password"] = current.password + else: + candidate["password"] = "" + config = SMTPConfig.from_mapping(candidate) + self._records.set( + _SMTP_RECORD_TYPE, _SMTP_RECORD_KEY, + json.dumps(config.as_record(), ensure_ascii=False, separators=(",", ":")), + ) + return config + + def public_status(self) -> dict[str, str | int | bool]: + config = self.get() + return {"configured": False} if config is None else config.public_status() + + +def send_verification_code(config: SMTPConfig, recipient_email: str, code: str, *, + timeout: int | float = 10) -> None: + """Send one six-digit registration code; all transport errors are redacted.""" + + recipient = validate_email(recipient_email) + if not isinstance(code, str) or not _SIX_DIGITS.fullmatch(code): + raise SMTPError("验证码格式无效") + if (isinstance(timeout, bool) or not isinstance(timeout, (int, float)) + or not 0 < timeout <= 30): + raise SMTPError("SMTP 连接超时设置无效") + + message = EmailMessage() + message["From"] = config.from_address + message["To"] = recipient + message["Subject"] = "Virsh Panel 注册验证码" + message["Auto-Submitted"] = "auto-generated" + message.set_content( + f"您的注册验证码是:{code}\n\n验证码在 10 分钟内有效,请勿转发给他人。\n" + "如果不是您本人操作,请忽略这封邮件。\n", + charset="utf-8", + ) + + try: + context = ssl.create_default_context() + if config.tls_mode == "ssl": + client = smtplib.SMTP_SSL( + config.host, config.port, timeout=timeout, context=context, + ) + else: + client = smtplib.SMTP(config.host, config.port, timeout=timeout) + with client: + client.ehlo() + if config.tls_mode == "starttls": + client.starttls(context=context) + client.ehlo() + if config.username: + client.login(config.username, config.password) + refused = client.send_message(message) + if refused: + raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502) + except (smtplib.SMTPException, OSError): + raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502) from None diff --git a/engine/virsh_panel/ssh_agent.py b/engine/virsh_panel/ssh_agent.py new file mode 100644 index 00000000..3f1a8fd3 --- /dev/null +++ b/engine/virsh_panel/ssh_agent.py @@ -0,0 +1,371 @@ +"""A private, short-lived OpenSSH agent for one saved host generation. + +The key passphrase is handed to ``ssh-add`` through a one-shot inherited pipe +and an askpass helper. It is never put in an argument, environment value, or +file. The agent keeps the unlocked identity only for this panel process. +""" + +from __future__ import annotations + +import base64 +import binascii +import ctypes +import os +import secrets +import select +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path + + +class SSHAgentError(Exception): + """A safe, user-facing agent error that contains no credentials.""" + + +_ASKPASS_SOURCE = b"""#!/usr/bin/python3 +import os +import sys + +try: + fd = int(os.environ["VIRSH_PANEL_ASKPASS_FD"]) + parts = [] + size = 0 + while True: + part = os.read(fd, 1024) + if not part: + break + size += len(part) + if size > 1023: + sys.exit(1) + parts.append(part) + if size == 0: + sys.exit(1) + os.write(1, b"".join(parts)) +except (KeyError, ValueError, OSError): + sys.exit(1) +""" + + +def _command(name: str) -> str: + executable = shutil.which(name) + if executable is None: + raise SSHAgentError(f"面板服务器缺少 {name} 命令") + return str(Path(executable).resolve()) + + +def _agent_environment(socket_path: Path) -> dict[str, str]: + environment = os.environ.copy() + environment["SSH_AUTH_SOCK"] = str(socket_path) + return environment + + +def _safe_public_key(value: str) -> str: + lines = value.splitlines() + if len(lines) != 1: + raise SSHAgentError("SSH agent 未能确认唯一的私钥身份") + fields = lines[0].split() + if len(fields) < 2 or not fields[0].startswith(("ssh-", "ecdsa-", "sk-")): + raise SSHAgentError("SSH agent 返回的公钥格式无效") + try: + fields[0].encode("ascii") + fields[1].encode("ascii") + blob = base64.b64decode(fields[1], validate=True) + except (binascii.Error, UnicodeEncodeError, ValueError) as exc: + raise SSHAgentError("SSH agent 返回的公钥格式无效") from exc + if not 16 <= len(blob) <= 8192: + raise SSHAgentError("SSH agent 返回的公钥格式无效") + return f"{fields[0]} {fields[1]}" + + +class SSHAgentSession: + """Own one foreground ``ssh-agent`` and its single unlocked identity.""" + + def __init__(self, generation: Path, key_path: Path, passphrase: str) -> None: + generation = Path(generation).absolute() + key_path = Path(key_path).absolute() + if ( + generation.is_symlink() + or not generation.is_dir() + or key_path.is_symlink() + or not key_path.is_file() + or key_path.parent != generation + ): + raise SSHAgentError("SSH 密钥配置目录无效") + if not isinstance(passphrase, str): + raise SSHAgentError("SSH 私钥口令格式无效") + if any(character in passphrase for character in "\r\n\x00"): + raise SSHAgentError("SSH 私钥口令不能包含换行或 NUL 字符") + try: + passphrase_bytes = passphrase.encode("utf-8") + except UnicodeEncodeError as exc: + raise SSHAgentError("SSH 私钥口令格式无效") from exc + if len(passphrase_bytes) > 1023: + raise SSHAgentError("SSH 私钥口令不能超过 1023 个 UTF-8 字节") + + self.socket_path = generation / ("agent-" + secrets.token_hex(8) + ".sock") + self.public_key = "" + self._process: subprocess.Popen[bytes] | None = None + self._helper_path: Path | None = None + self._watchdog_write_fd: int | None = None + if len(os.fsencode(self.socket_path)) >= 100: + raise SSHAgentError("面板数据目录路径过长,无法创建 SSH agent socket") + try: + self._start() + self.public_key = self._load_key(key_path, passphrase_bytes) + except SSHAgentError: + self.close() + raise + except (OSError, subprocess.TimeoutExpired): + self.close() + raise SSHAgentError("SSH agent 启动或解锁失败") from None + + def _start(self) -> None: + if self.socket_path.exists() or self.socket_path.is_symlink(): + raise SSHAgentError("SSH agent socket 路径已被占用") + try: + if sys.platform == "linux": + # PR_SET_PDEATHSIG observes the *creating thread*, not the + # whole panel process. A FastAPI worker thread can end while + # the panel remains live, so a single-threaded supervisor + # watches a pipe whose writer belongs to the panel process. + read_fd, write_fd = os.pipe() + self._watchdog_write_fd = write_fd + try: + self._process = subprocess.Popen( + [ + sys.executable, + str(Path(__file__).resolve()), + "--agent-supervisor", + str(read_fd), + _command("ssh-agent"), + str(self.socket_path), + ], + pass_fds=(read_fd,), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + ) + finally: + os.close(read_fd) + else: + self._process = subprocess.Popen( + [_command("ssh-agent"), "-D", "-a", str(self.socket_path)], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + ) + except OSError: + raise SSHAgentError("SSH agent 无法启动") from None + deadline = time.monotonic() + 3 + while time.monotonic() < deadline: + if self._process.poll() is not None: + raise SSHAgentError("SSH agent 启动后立即退出") + if self.socket_path.is_socket(): + return + time.sleep(0.02) + raise SSHAgentError("SSH agent 启动超时") + + def _create_helper(self) -> Path: + helper = self.socket_path.parent / ("askpass-" + secrets.token_hex(8)) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + descriptor = os.open(helper, flags, 0o700) + try: + with os.fdopen(descriptor, "wb") as output: + os.fchmod(output.fileno(), 0o700) + output.write(_ASKPASS_SOURCE) + output.flush() + os.fsync(output.fileno()) + except BaseException: + helper.unlink(missing_ok=True) + raise + self._helper_path = helper + return helper + + def _load_key(self, key_path: Path, passphrase: bytes) -> str: + helper = self._create_helper() + read_fd, write_fd = os.pipe() + try: + if passphrase: + os.write(write_fd, passphrase) + os.close(write_fd) + write_fd = -1 + environment = _agent_environment(self.socket_path) + environment.update( + { + "SSH_ASKPASS": str(helper), + "SSH_ASKPASS_REQUIRE": "force", + "VIRSH_PANEL_ASKPASS_FD": str(read_fd), + } + ) + loaded = subprocess.run( + [_command("ssh-add"), "-k", "-q", str(key_path)], + env=environment, + pass_fds=(read_fd,), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=12, + check=False, + ) + finally: + os.close(read_fd) + if write_fd != -1: + os.close(write_fd) + helper.unlink(missing_ok=True) + self._helper_path = None + if loaded.returncode != 0: + raise SSHAgentError("SSH 私钥无法解锁;请检查私钥内容和口令") + listed = subprocess.run( + [_command("ssh-add"), "-L"], + env=_agent_environment(self.socket_path), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + timeout=5, + check=False, + ) + if listed.returncode != 0: + raise SSHAgentError("SSH agent 未能读取已解锁的公钥") + return _safe_public_key(listed.stdout) + + @property + def alive(self) -> bool: + if self._process is None or self._process.poll() is not None: + return False + if not self.socket_path.is_socket(): + return False + try: + result = subprocess.run( + [_command("ssh-add"), "-l"], + env=_agent_environment(self.socket_path), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=2, + check=False, + ) + except (OSError, subprocess.TimeoutExpired, SSHAgentError): + return False + return result.returncode == 0 + + def close(self) -> None: + process = self._process + self._process = None + watchdog_write_fd = self._watchdog_write_fd + self._watchdog_write_fd = None + if watchdog_write_fd is not None: + try: + os.close(watchdog_write_fd) + except OSError: + pass + if process is not None: + try: + if process.poll() is None: + if watchdog_write_fd is None: + process.terminate() + process.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + try: + process.terminate() + process.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + try: + process.kill() + process.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + pass + if self._helper_path is not None: + self._helper_path.unlink(missing_ok=True) + self._helper_path = None + if process is not None: + try: + if self.socket_path.is_socket(): + self.socket_path.unlink() + except OSError: + pass + + +def _agent_child(expected_parent_pid: int, agent_binary: str, socket_path: str) -> int: + """Set Linux parent-death SIGTERM, then replace this process with agent.""" + if sys.platform != "linux" or expected_parent_pid <= 1: + return 1 + try: + prctl = ctypes.CDLL(None, use_errno=True).prctl + prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong] + prctl.restype = ctypes.c_int + if prctl(1, signal.SIGTERM, 0, 0, 0) != 0: # PR_SET_PDEATHSIG + return 1 + # The supervisor may have died before prctl took effect. + if os.getppid() != expected_parent_pid: + return 1 + os.execv(agent_binary, [agent_binary, "-D", "-a", socket_path]) + except (AttributeError, OSError): + return 1 + return 1 + + +def _agent_supervisor(read_fd: int, agent_binary: str, socket_path: str) -> int: + """End the agent when the panel closes its pipe, including on SIGKILL.""" + if sys.platform != "linux" or read_fd < 3: + return 1 + child: subprocess.Popen[bytes] | None = None + try: + child = subprocess.Popen( + [ + sys.executable, + str(Path(__file__).resolve()), + "--agent-child", + str(os.getpid()), + agent_binary, + socket_path, + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + ) + poller = select.poll() + poller.register(read_fd, select.POLLIN | select.POLLHUP | select.POLLERR) + while True: + if child.poll() is not None: + return 1 + if poller.poll(100): + return 0 + except (OSError, ValueError): + return 1 + finally: + if child is not None and child.poll() is None: + try: + child.terminate() + child.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + try: + child.kill() + child.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + pass + try: + if Path(socket_path).is_socket(): + Path(socket_path).unlink() + except OSError: + pass + try: + os.close(read_fd) + except OSError: + pass + + +if __name__ == "__main__": + if len(sys.argv) == 5 and sys.argv[1] == "--agent-supervisor": + raise SystemExit(_agent_supervisor(int(sys.argv[2]), sys.argv[3], sys.argv[4])) + if len(sys.argv) == 5 and sys.argv[1] == "--agent-child": + raise SystemExit(_agent_child(int(sys.argv[2]), sys.argv[3], sys.argv[4])) + raise SystemExit(1) diff --git a/engine/virsh_panel/ssh_keys.py b/engine/virsh_panel/ssh_keys.py new file mode 100644 index 00000000..ea18d03d --- /dev/null +++ b/engine/virsh_panel/ssh_keys.py @@ -0,0 +1,165 @@ +"""Per-account OpenSSH public keys for cloud-image guest access. + +Only public key material is stored. Every lookup and mutation includes the +authenticated user's database ID, so an ID from another account is not an +authorization bypass. The unique fingerprint is calculated from the decoded +SSH wire-format blob, independent of whitespace or a trailing comment. +""" + +from __future__ import annotations + +import base64 +import hashlib +import time +from typing import Any + +from .cloud_init import _validate_ssh_public_key +from .database import DatabaseError, DatabaseStore, pymysql + + +class SSHKeyError(Exception): + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +def _user_id(value: int) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError("Invalid user ID") + return value + + +def _key_id(value: int) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError("Invalid SSH key ID") + return value + + +def _name(value: str) -> str: + if (not isinstance(value, str) or value != value.strip() + or not 1 <= len(value) <= 80 + or any(ord(char) < 32 or ord(char) == 127 for char in value)): + raise SSHKeyError("公钥名称须为 1 至 80 个非控制字符") + return value + + +def _public_key(value: str) -> tuple[str, str]: + try: + validated = _validate_ssh_public_key(value) + except ValueError as exc: + raise SSHKeyError(str(exc)) from exc + key_type, encoded = validated.split(maxsplit=2)[:2] + blob = base64.b64decode(encoded, validate=True) + # Comments are operator hints, not key material. The user-chosen name is + # retained instead, and the canonical form avoids charset surprises. + canonical = f"{key_type} {base64.b64encode(blob).decode('ascii')}" + fingerprint = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode("ascii").rstrip("=") + return canonical, fingerprint + + +def _row(row: dict[str, Any] | None) -> dict[str, Any] | None: + if row is None: + return None + return { + "id": int(row["id"]), + "name": row["name"], + "public_key": row["public_key"], + "fingerprint": row["fingerprint"], + "created_at": int(row["created_at"]), + } + + +class DatabaseSSHKeyStore: + """MariaDB-backed key library with owner-scoped SQL queries.""" + + def __init__(self, store: DatabaseStore) -> None: + self._store = store + + def _connect(self): + return self._store._connect() + + def list_for_user(self, user_id: int) -> list[dict[str, Any]]: + _user_id(user_id) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, name, public_key, fingerprint, created_at " + "FROM user_ssh_keys WHERE user_id=%s ORDER BY created_at DESC, id DESC", + (user_id,), + ) + return [_row(row) for row in cursor.fetchall()] + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取 SSH 公钥") from exc + finally: + connection.close() + + def create_for_user(self, user_id: int, name: str, public_key: str, + *, now: int | None = None) -> dict[str, Any]: + _user_id(user_id) + name = _name(name) + public_key, fingerprint = _public_key(public_key) + timestamp = int(time.time()) if now is None else now + if isinstance(timestamp, bool) or not isinstance(timestamp, int) or timestamp < 0: + raise ValueError("Invalid SSH key creation time") + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "INSERT INTO user_ssh_keys " + "(user_id, name, public_key, fingerprint, created_at) " + "VALUES (%s, %s, %s, %s, %s)", + (user_id, name, public_key, fingerprint, timestamp), + ) + key_id = cursor.lastrowid + connection.commit() + return { + "id": key_id, "name": name, "public_key": public_key, + "fingerprint": fingerprint, "created_at": timestamp, + } + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + raise SSHKeyError("此 SSH 公钥已添加到当前账户", 409) from exc + raise DatabaseError("无法保存 SSH 公钥") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法保存 SSH 公钥") from exc + finally: + connection.close() + + def get_for_user(self, user_id: int, key_id: int) -> dict[str, Any] | None: + _user_id(user_id) + _key_id(key_id) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, name, public_key, fingerprint, created_at " + "FROM user_ssh_keys WHERE user_id=%s AND id=%s", + (user_id, key_id), + ) + return _row(cursor.fetchone()) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取 SSH 公钥") from exc + finally: + connection.close() + + def delete_for_user(self, user_id: int, key_id: int) -> bool: + _user_id(user_id) + _key_id(key_id) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "DELETE FROM user_ssh_keys WHERE user_id=%s AND id=%s", + (user_id, key_id), + ) + deleted = cursor.rowcount > 0 + connection.commit() + return deleted + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法删除 SSH 公钥") from exc + finally: + connection.close() diff --git a/engine/virsh_panel/update_worker.py b/engine/virsh_panel/update_worker.py new file mode 100644 index 00000000..39bb6799 --- /dev/null +++ b/engine/virsh_panel/update_worker.py @@ -0,0 +1,109 @@ +"""Entry point for the separate virsh-panel-update.service one-shot unit.""" + +from __future__ import annotations + +import argparse +import json +import logging +import subprocess +import time +from urllib.error import URLError +from urllib.request import urlopen + +from .config import PROJECT_DIR, Settings +from .database import DatabaseError, DatabaseStore +from .database_bootstrap import DatabaseBootstrap +from .updater import UpdateError, Updater + + +LOG = logging.getLogger(__name__) +_WEB_UNIT = "virsh-panel.service" +_HEALTH_URL = "http://127.0.0.1:8000/api/v1/health" + + +def restart_web_service() -> None: + """Restart the main unit and wait for its local health endpoint.""" + try: + result = subprocess.run( + ["/usr/bin/systemctl", "restart", _WEB_UNIT], + capture_output=True, + text=True, + timeout=90, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise UpdateError("面板服务重启失败,请检查 systemd 日志", 500) from exc + if result.returncode != 0: + # systemctl output is intentionally not returned: it may contain + # environment details from another unit or configuration. + raise UpdateError("面板服务重启失败,请检查 systemd 日志", 500) + + deadline = time.monotonic() + 45 + while time.monotonic() < deadline: + try: + with urlopen(_HEALTH_URL, timeout=2) as response: + payload = json.load(response) + if response.status == 200 and isinstance(payload, dict) and payload.get("status") == "ok": + return + except (OSError, URLError, ValueError): + pass + time.sleep(1) + raise UpdateError("新版本服务未通过本机健康检查,请检查面板日志", 500) + + +def _load_updater() -> tuple[Updater, DatabaseStore]: + settings = Settings.from_env() + bootstrap = DatabaseBootstrap(settings.data_dir) + config = bootstrap.load_config() + if config is None: + raise UpdateError("尚未完成数据库配置,无法运行在线更新", 409) + store = DatabaseStore(config, bootstrap.master_key()) + return Updater(PROJECT_DIR, store), store + + +def finalize_incomplete_job(updater: Updater, store: DatabaseStore) -> bool: + """Mark an interrupted job failed after the one-shot unit has exited. + + This is invoked by systemd ExecStopPost regardless of the main worker's + exit code. Successful/failed jobs are untouched. It is intentionally + idempotent so operators may rerun it while diagnosing a crashed worker. + """ + job_id = store.get_value("update.active_job") + if not job_id: + return False + job = updater.get_job(job_id) + if job is None or job.get("status") not in {"queued", "running"}: + return False + updater.fail_job( + job_id, + "独立更新服务异常退出或超时;请检查更新服务日志和当前 Git 版本,勿直接重复提交", + ) + return True + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Run or finalize the Virsh Panel update job") + parser.add_argument("--finalize-incomplete", action="store_true") + options = parser.parse_args(argv) + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + try: + updater, store = _load_updater() + if options.finalize_incomplete: + if finalize_incomplete_job(updater, store): + LOG.warning("interrupted panel update marked failed") + return 0 + result = updater.run_pending_job(restart=restart_web_service) + except (UpdateError, DatabaseError, ValueError) as exc: + # Public errors are deliberately credential-free. Never log the DB + # config, Gitea PAT, subprocess output or captured environment. + LOG.error("panel update failed: %s", exc) + return 1 + LOG.info( + "panel update finished: job=%s old=%s new=%s updated=%s", + result["job_id"], result.get("old_commit"), result.get("new_commit"), result.get("updated"), + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/engine/virsh_panel/updater.py b/engine/virsh_panel/updater.py new file mode 100644 index 00000000..1bd7270f --- /dev/null +++ b/engine/virsh_panel/updater.py @@ -0,0 +1,539 @@ +"""Conservative Git updater for the panel's own, fixed Gitea repository. + +The web process may inspect a checkout and enqueue a job. ``run_pending_job`` +must run in a separate, privileged one-shot service: the regular web service +has a read-only code directory, and restarting it from within a request is +unreliable. The caller supplies the restart/health-check callback. + +The personal access token is stored by the injected encrypted database store. +It never appears in a Git URL, command argument, temporary file, or returned +API data. A private, short-lived askpass program receives it only in the +child's environment while an HTTPS Git operation is in progress. +""" + +from __future__ import annotations + +import fcntl +import json +import os +import re +import secrets +import stat +import subprocess +import tempfile +import threading +import time +from contextlib import contextmanager +from pathlib import Path +from typing import Callable, Protocol + + +REPOSITORY_URL = "https://g.luoli.live/root/virt.git" +BRANCH = "main" +_TOKEN_KEY = "update.gitea_access_token" +_ACTIVE_JOB_KEY = "update.active_job" +_JOB_PREFIX = "update.job." +_HEX_COMMIT = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") +_JOB_ID = re.compile(r"[A-Za-z0-9_-]{16,64}\Z") + + +class UpdateStore(Protocol): + """Small persistence surface supplied by the encrypted database layer.""" + + def get_secret(self, name: str) -> str | None: ... + + def set_secret(self, name: str, value: str) -> None: ... + + def delete_secret(self, name: str) -> None: ... + + def get_value(self, name: str) -> str | None: ... + + def set_value(self, name: str, value: str) -> None: ... + + +class UpdateError(Exception): + """A safe error suitable for returning to the authenticated operator.""" + + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +class Updater: + """Read/check/advance only the pinned ``main`` branch of the panel repo.""" + + def __init__( + self, + repo_dir: Path, + secret_store: UpdateStore, + *, + git_binary: str = "git", + runner: Callable[..., subprocess.CompletedProcess[str]] | None = None, + ) -> None: + self.repo_dir = Path(repo_dir).absolute() + self.store = secret_store + self.git_binary = git_binary + self._run = runner or subprocess.run + self._lock = threading.RLock() + + def settings(self) -> dict: + """Return only public configuration, never the stored access token.""" + active_id = self.store.get_value(_ACTIVE_JOB_KEY) + active_job = self.get_job(active_id) if active_id else None + result = { + "repository": REPOSITORY_URL, + "branch": BRANCH, + "token_configured": bool(self.store.get_secret(_TOKEN_KEY)), + "checkout_ready": False, + "current_commit": None, + "last_job_id": active_id if active_job is not None else None, + "active_job_id": ( + active_id if active_job is not None + and active_job.get("status") in {"queued", "running"} else None + ), + } + try: + result["current_commit"] = self._checkout_head(require_clean=False) + result["checkout_ready"] = True + except UpdateError as exc: + result["checkout_error"] = str(exc) + return result + + def set_token(self, token: str) -> None: + if ( + not isinstance(token, str) + or not 16 <= len(token) <= 4096 + or token != token.strip() + or any(ord(char) < 33 or ord(char) > 126 for char in token) + ): + raise UpdateError("Gitea 访问令牌格式无效") + self.store.set_secret(_TOKEN_KEY, token) + + def clear_token(self) -> None: + self.store.delete_secret(_TOKEN_KEY) + + def _environment(self) -> dict[str, str]: + # Do not inherit GIT_TRACE, Git configuration, proxy overrides or + # GIT_SSL_NO_VERIFY from the panel service environment. + return { + "PATH": os.defpath, + "LANG": "C", + "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_TERMINAL_PROMPT": "0", + "GIT_OPTIONAL_LOCKS": "0", + "GIT_ALLOW_PROTOCOL": "https", + } + + @contextmanager + def _git_auth(self): + token = self.store.get_secret(_TOKEN_KEY) + if not token: + raise UpdateError("请先在面板中设置 Gitea 访问令牌", 409) + with tempfile.TemporaryDirectory(prefix="virsh-panel-askpass-") as directory: + askpass = Path(directory) / "askpass" + # This script contains no credential. Git passes a prompt as one + # argument; the token is handed to the Git child only in memory. + askpass.write_text( + "#!/bin/sh\n" + "case \"$1\" in\n" + " *sername*|*SERNAM*) printf '%s\\n' \"$VIRSH_PANEL_GIT_USERNAME\" ;;\n" + " *assword*|*ASSWORD*) printf '%s\\n' \"$VIRSH_PANEL_GIT_TOKEN\" ;;\n" + " *) exit 1 ;;\n" + "esac\n", + encoding="ascii", + ) + askpass.chmod(0o700) + env = self._environment() + env.update({ + "GIT_ASKPASS": str(askpass), + "VIRSH_PANEL_GIT_USERNAME": "root", + "VIRSH_PANEL_GIT_TOKEN": token, + }) + yield env + + def _git( + self, + *args: str, + timeout: float = 15, + environment: dict[str, str] | None = None, + error: str = "Git 操作失败,请检查面板日志", + allowed_codes: tuple[int, ...] = (0,), + ) -> subprocess.CompletedProcess[str]: + argv = [ + self.git_binary, + "-c", "core.hooksPath=/dev/null", + "-c", "http.followRedirects=false", + "-c", "http.sslVerify=true", + "-c", "http.extraHeader=", + "-c", "credential.helper=", + "-c", "fetch.recurseSubmodules=false", + *args, + ] + try: + result = self._run( + argv, + cwd=self.repo_dir, + env=environment or self._environment(), + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + # Never include stderr, a URL, or a token in a public exception. + raise UpdateError(error, 502) from exc + if result.returncode not in allowed_codes: + raise UpdateError(error, 502) + return result + + def _checkout_head(self, *, require_clean: bool) -> str: + if self.repo_dir.is_symlink() or not self.repo_dir.is_dir(): + raise UpdateError("面板目录不是有效的 Git 检出目录", 409) + repo_info = self.repo_dir.lstat() + if repo_info.st_uid != os.geteuid() or repo_info.st_mode & 0o022: + raise UpdateError("面板目录必须由当前服务账号拥有,且不能允许组或其他用户写入", 409) + git_dir = self.repo_dir / ".git" + if git_dir.is_symlink() or not git_dir.is_dir(): + raise UpdateError("面板必须从完整 Git 仓库部署,不能使用压缩包或工作树", 409) + try: + info = git_dir.lstat() + except OSError as exc: + raise UpdateError("无法读取面板 Git 仓库", 409) from exc + if not stat.S_ISDIR(info.st_mode): + raise UpdateError("面板 Git 仓库格式无效", 409) + if info.st_uid != os.geteuid() or info.st_mode & 0o022: + raise UpdateError("面板 Git 仓库权限不安全,已拒绝在线更新", 409) + + top = self._git("rev-parse", "--show-toplevel", error="无法识别面板 Git 仓库").stdout.strip() + if Path(top).resolve() != self.repo_dir.resolve(): + raise UpdateError("Git 仓库根目录与面板程序目录不一致", 409) + branch = self._git( + "symbolic-ref", "--quiet", "--short", "HEAD", + error="面板 Git 仓库当前不是 main 分支", + ).stdout.strip() + if branch != BRANCH: + raise UpdateError("面板只允许从 main 分支更新", 409) + configured_urls = self._git( + "config", "--local", "--get-all", "remote.origin.url", + error="面板 Git 仓库缺少 origin 地址", + ).stdout.splitlines() + if configured_urls != [REPOSITORY_URL]: + raise UpdateError("Git origin 必须是已指定的 Gitea 私有仓库,且不得包含凭据", 409) + # url.*.insteadOf could silently rewrite our explicit HTTPS URL to a + # different server and disclose the access token. Refuse it outright. + rewrites = self._git( + "config", "--local", "--name-only", "--get-regexp", r"^url\..*\.insteadof$", + allowed_codes=(0, 1), + error="无法检查 Git URL 重写配置", + ) + if rewrites.returncode == 0: + raise UpdateError("Git 仓库配置了 URL 重写,无法安全更新", 409) + head = self._git("rev-parse", "HEAD", error="无法读取当前面板版本").stdout.strip() + if not _HEX_COMMIT.fullmatch(head): + raise UpdateError("当前 Git 提交标识无效", 409) + if require_clean: + status = self._git( + "status", "--porcelain=v1", "--untracked-files=all", + error="无法检查面板文件变更", + ).stdout + if status.strip(): + raise UpdateError("面板目录存在未提交或未跟踪文件;为防止覆盖,请先处理这些文件", 409) + return head + + def _remote_head(self) -> str: + with self._git_auth() as env: + output = self._git( + "ls-remote", "--exit-code", "--", REPOSITORY_URL, f"refs/heads/{BRANCH}", + environment=env, + timeout=45, + error="无法读取 Gitea 私有仓库;请检查访问令牌、TLS 证书和网络", + ).stdout.strip() + fields = output.split() + if len(fields) != 2 or fields[1] != f"refs/heads/{BRANCH}" or not _HEX_COMMIT.fullmatch(fields[0]): + raise UpdateError("Gitea 返回了无效的分支信息", 502) + return fields[0] + + def check(self) -> dict: + """Inspect the remote head without altering the local checkout.""" + with self._lock: + current = self._checkout_head(require_clean=True) + remote = self._remote_head() + return { + "repository": REPOSITORY_URL, + "branch": BRANCH, + "current_commit": current, + "remote_commit": remote, + "status": "current" if current == remote else "update_available", + } + + def _fetch_remote(self) -> str: + with self._git_auth() as env: + self._git( + "fetch", "--no-tags", "--no-recurse-submodules", "--", + REPOSITORY_URL, f"refs/heads/{BRANCH}", + environment=env, + timeout=300, + error="无法从 Gitea 拉取更新;请检查访问令牌、TLS 证书和网络", + ) + head = self._git("rev-parse", "FETCH_HEAD", error="无法识别已下载的更新版本").stdout.strip() + if not _HEX_COMMIT.fullmatch(head): + raise UpdateError("下载的 Git 提交标识无效", 502) + return head + + def _assert_safe_tree(self, target: str) -> None: + listing = self._git( + "ls-tree", "-r", "--name-only", target, "--", "data", ".venv", ".gitmodules", + error="无法检查更新文件清单", + ).stdout + if listing: + raise UpdateError("更新包含面板数据目录、虚拟环境或子模块配置,已拒绝覆盖", 409) + + def _install_requirements(self, target: str) -> None: + venv = self.repo_dir / ".venv" + python = venv / "bin" / "python" + if venv.is_symlink() or not venv.is_dir() or not python.exists(): + raise UpdateError("未找到面板虚拟环境 .venv,不能自动安装更新依赖", 409) + requirements = self._git( + "show", f"{target}:requirements.txt", + error="更新版本缺少 requirements.txt,已取消更新", + ).stdout + if not requirements or len(requirements) > 262144: + raise UpdateError("更新版本的依赖清单无效", 409) + with tempfile.TemporaryDirectory(prefix="virsh-panel-requirements-") as directory: + path = Path(directory) / "requirements.txt" + path.write_text(requirements, encoding="utf-8") + path.chmod(0o600) + env = { + "PATH": os.defpath, + "LANG": "C", + "LC_ALL": "C", + "PIP_NO_INPUT": "1", + "PIP_NO_CACHE_DIR": "1", + "PIP_DISABLE_PIP_VERSION_CHECK": "1", + } + try: + result = self._run( + [str(python), "-m", "pip", "install", "--no-input", "-r", str(path)], + cwd=self.repo_dir, + env=env, + capture_output=True, + text=True, + timeout=900, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise UpdateError("更新依赖安装失败;面板代码尚未切换", 502) from exc + if result.returncode != 0: + raise UpdateError("更新依赖安装失败;面板代码尚未切换", 502) + + @contextmanager + def _apply_lock(self): + git_dir = self.repo_dir / ".git" + flags = os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(git_dir / "virsh-panel-update.lock", flags, 0o600) + except OSError as exc: + raise UpdateError("无法获取面板更新锁;请确认独立更新服务有代码目录写权限", 500) from exc + try: + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: + raise UpdateError("面板更新锁文件权限不安全", 500) + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + os.close(descriptor) + raise UpdateError("另一个更新任务正在运行", 409) from exc + except BaseException: + os.close(descriptor) + raise + try: + yield + finally: + fcntl.flock(descriptor, fcntl.LOCK_UN) + os.close(descriptor) + + def apply( + self, *, progress: Callable[[str], None] | None = None, + expected_current_commit: str | None = None, + expected_remote_commit: str | None = None, + ) -> dict: + """Install dependencies, then fast-forward code. No force/reset is used.""" + report = progress or (lambda _phase: None) + with self._lock: + # Validate before creating a lock inside .git. + current = self._checkout_head(require_clean=True) + with self._apply_lock(): + # Re-check after acquiring the cross-process lock. + current = self._checkout_head(require_clean=True) + if expected_current_commit is not None and current != expected_current_commit: + raise UpdateError("面板本地版本已变化,请重新检查更新后再执行", 409) + report("正在从 Gitea 下载更新") + target = self._fetch_remote() + if expected_remote_commit is not None and target != expected_remote_commit: + raise UpdateError("Gitea main 分支已变化,请重新检查更新后再执行", 409) + self._assert_safe_tree(target) + ancestry = self._git( + "merge-base", "--is-ancestor", current, target, + allowed_codes=(0, 1), + error="无法验证更新提交历史", + ) + if ancestry.returncode != 0: + raise UpdateError("远端 main 分支与当前版本已分叉,已拒绝自动覆盖", 409) + if target == current: + return {"updated": False, "old_commit": current, "new_commit": target} + report("正在安装新版本依赖") + self._install_requirements(target) + # Keep an immutable rollback pointer for manual recovery. A + # forced reset is never part of the automatic update path. + rollback_ref = f"refs/virsh-panel/rollback/{int(time.time())}-{secrets.token_hex(4)}" + self._git( + "update-ref", rollback_ref, current, + error="无法保存更新前版本,已取消切换", + ) + # Files may have been edited during a long dependency install. + self._checkout_head(require_clean=True) + report("正在切换到新版本") + self._git( + "merge", "--ff-only", "--no-stat", target, + timeout=120, + error="无法快进更新代码;请检查面板目录与 Git 日志", + ) + installed = self._checkout_head(require_clean=True) + if installed != target: + raise UpdateError("更新后的 Git 提交与预期不符,请人工核查", 500) + return { + "updated": True, + "old_commit": current, + "new_commit": target, + "rollback_ref": rollback_ref, + } + + def _job_key(self, job_id: str) -> str: + if not isinstance(job_id, str) or not _JOB_ID.fullmatch(job_id): + raise UpdateError("更新任务编号无效", 404) + return _JOB_PREFIX + job_id + + def get_job(self, job_id: str) -> dict | None: + raw = self.store.get_value(self._job_key(job_id)) + if raw is None: + return None + try: + job = json.loads(raw) + except (TypeError, ValueError) as exc: + raise UpdateError("更新任务记录损坏", 500) from exc + if not isinstance(job, dict) or job.get("job_id") != job_id: + raise UpdateError("更新任务记录损坏", 500) + return job + + def _save_job(self, job: dict) -> None: + self.store.set_value(self._job_key(job["job_id"]), json.dumps(job, ensure_ascii=False)) + + def create_job( + self, *, expected_current_commit: str | None = None, + expected_remote_commit: str | None = None, + ) -> dict: + """Enqueue one persisted job; the web layer then starts the worker.""" + with self._lock: + current = self._checkout_head(require_clean=True) + if expected_current_commit is not None: + if not _HEX_COMMIT.fullmatch(expected_current_commit): + raise UpdateError("要更新的当前版本标识无效", 422) + if current != expected_current_commit: + raise UpdateError("面板本地版本已变化,请重新检查更新后再执行", 409) + if not self.store.get_secret(_TOKEN_KEY): + raise UpdateError("请先在面板中设置 Gitea 访问令牌", 409) + if expected_remote_commit is not None: + if not _HEX_COMMIT.fullmatch(expected_remote_commit): + raise UpdateError("要更新的远端版本标识无效", 422) + if self._remote_head() != expected_remote_commit: + raise UpdateError("Gitea main 分支已变化,请重新检查更新后再执行", 409) + active_id = self.store.get_value(_ACTIVE_JOB_KEY) + if active_id: + active = self.get_job(active_id) + if active is not None and active.get("status") in {"queued", "running"}: + raise UpdateError("已有更新任务正在执行", 409) + job_id = secrets.token_urlsafe(18) + job = { + "job_id": job_id, + "status": "queued", + "phase": "等待独立更新服务启动", + "created_at": int(time.time()), + } + if expected_current_commit is not None: + job["expected_current_commit"] = expected_current_commit + if expected_remote_commit is not None: + job["expected_remote_commit"] = expected_remote_commit + self._save_job(job) + self.store.set_value(_ACTIVE_JOB_KEY, job_id) + return job.copy() + + def fail_job(self, job_id: str, message: str) -> dict: + """Mark a queued/running job failed if the service could not start.""" + with self._lock: + job = self.get_job(job_id) + if job is None: + raise UpdateError("更新任务不存在", 404) + if job["status"] not in {"queued", "running"}: + return job + job.update(status="failed", phase="更新失败", error=str(message)[:300], finished_at=int(time.time())) + self._save_job(job) + return job.copy() + + def run_pending_job(self, *, restart: Callable[[], None] | None = None) -> dict: + """Run the queued job in a separate service and persist every phase. + + ``restart`` should restart the web unit and, ideally, verify its health. + If it fails, the job records that code may already have changed and + exposes the old commit/rollback ref for operator-led recovery. + """ + with self._lock: + job_id = self.store.get_value(_ACTIVE_JOB_KEY) + if not job_id: + raise UpdateError("没有待执行的更新任务", 404) + job = self.get_job(job_id) + if job is None or job.get("status") != "queued": + raise UpdateError("更新任务未处于等待状态;请人工核查后重新提交", 409) + job.update(status="running", phase="正在检查本地仓库", started_at=int(time.time())) + self._save_job(job) + + def progress(phase: str) -> None: + with self._lock: + job["phase"] = str(phase)[:200] + self._save_job(job) + + applied: dict | None = None + try: + applied = self.apply( + progress=progress, + expected_current_commit=job.get("expected_current_commit"), + expected_remote_commit=job.get("expected_remote_commit"), + ) + job.update(applied) + self._save_job(job) + if applied["updated"] and restart is not None: + progress("正在重启面板并检查服务") + restart() + elif applied["updated"]: + # A worker that cannot restart the web service must not + # report a successful one-click update. + raise UpdateError("代码已更新,但未配置自动重启;请人工重启面板服务", 500) + job.update(status="succeeded", phase="更新完成" if applied["updated"] else "已是最新版本", + finished_at=int(time.time())) + self._save_job(job) + return job.copy() + except Exception as exc: + if isinstance(exc, UpdateError): + error = str(exc) + else: + error = "更新失败,请查看独立更新服务日志" + if applied is not None and applied.get("updated"): + error += ";程序代码可能已切换,请人工核查并重启或按回滚引用恢复" + job.update(status="failed", phase="更新失败", error=error, finished_at=int(time.time())) + self._save_job(job) + if isinstance(exc, UpdateError): + raise + raise UpdateError(error, 500) from exc + + +__all__ = ["BRANCH", "REPOSITORY_URL", "UpdateError", "UpdateStore", "Updater"] diff --git a/engine/virsh_panel/users.py b/engine/virsh_panel/users.py new file mode 100644 index 00000000..04648e83 --- /dev/null +++ b/engine/virsh_panel/users.py @@ -0,0 +1,497 @@ +"""MariaDB user accounts, registration codes, and VM ownership. + +The panel's public registration code is only six digits, so its stored +fingerprint is keyed with the database master key. A stolen database alone +cannot check guesses offline. Every SQL value is passed as a parameter. +""" + +from __future__ import annotations + +import hashlib +import hmac +import re +import secrets +import time +import uuid +from typing import Any + +from .auth import hash_password +from .database import DatabaseError, DatabaseStore, pymysql +from .panel_state import _USERNAME + + +_DOMAIN_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") +_LOCAL_PART = re.compile(r"[A-Za-z0-9_+%-](?:[A-Za-z0-9._+%-]{0,62}[A-Za-z0-9_+%-])?\Z") +_CODE = re.compile(r"[0-9]{6}\Z") +_HOST_SCOPE = re.compile(r"[0-9a-f]{64}\Z") +_MAX_CODE_ATTEMPTS = 5 + + +class UserError(Exception): + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +def normalize_email(email: str) -> str: + """Reject addresses that cannot be safely used in SMTP headers.""" + if not isinstance(email, str) or not 3 <= len(email) <= 254 or email != email.strip(): + raise UserError("邮箱地址格式无效") + try: + email.encode("ascii") + except UnicodeEncodeError as exc: + raise UserError("邮箱地址格式无效") from exc + if email.count("@") != 1: + raise UserError("邮箱地址格式无效") + local, domain = email.split("@") + if (len(local) > 64 or len(domain) > 253 or ".." in email + or not _LOCAL_PART.fullmatch(local) + or not all(_DOMAIN_LABEL.fullmatch(label) for label in domain.split(".")) + or "." not in domain): + raise UserError("邮箱地址格式无效") + return email.lower() + + +def _validate_username(username: str) -> str: + if not isinstance(username, str) or not _USERNAME.fullmatch(username): + raise UserError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符") + return username + + +def _validate_password(password: str) -> str: + if not isinstance(password, str) or not 12 <= len(password) <= 1024: + raise UserError("密码长度须在 12 至 1024 位之间") + return password + + +def _validate_clock(now: int | None) -> int: + value = int(time.time()) if now is None else now + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError("Invalid registration time") + return value + + +def _vm_identity(host_scope: str, vm_uuid: str) -> tuple[str, str]: + if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope): + raise ValueError("Invalid host scope") + try: + canonical_uuid = str(uuid.UUID(vm_uuid)) + except (ValueError, TypeError, AttributeError) as exc: + raise ValueError("Invalid VM UUID") from exc + return host_scope, canonical_uuid + + +def _user_row(row: dict[str, Any] | None) -> dict[str, Any] | None: + if row is None: + return None + return { + "id": int(row["id"]), + "username": row["username"], + "email": row["email"], + "password_hash": row["password_hash"], + "admin": bool(row["admin"]), + "approved": bool(row["approved"]), + "email_verified": bool(row["email_verified"]), + "created_at": int(row["created_at"]), + } + + +class DatabaseUserStore: + """Users are plain SQL rows; password hashes and code digests are one-way.""" + + def __init__(self, store: DatabaseStore, code_key: bytes) -> None: + if not isinstance(code_key, bytes) or len(code_key) != 32: + raise ValueError("Registration code key must be 32 bytes") + self._store = store + self._code_key = code_key + + def _connect(self): + return self._store._connect() + + def _code_digest(self, email: str, code: str) -> str: + message = b"virsh-panel-registration-v1\x00" + email.encode("ascii") + b"\x00" + code.encode("ascii") + return hmac.new(self._code_key, message, hashlib.sha256).hexdigest() + + @staticmethod + def generate_code() -> str: + return f"{secrets.randbelow(1_000_000):06d}" + + def has_users(self) -> bool: + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("SELECT id FROM users LIMIT 1") + return cursor.fetchone() is not None + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取用户数据") from exc + finally: + connection.close() + + def get_by_username(self, username: str) -> dict[str, Any] | None: + if not isinstance(username, str) or not _USERNAME.fullmatch(username): + return None + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, username, email, password_hash, admin, approved, " + "email_verified, created_at " + "FROM users WHERE username=%s", (username,), + ) + return _user_row(cursor.fetchone()) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取用户数据") from exc + finally: + connection.close() + + def get_by_email(self, email: str) -> dict[str, Any] | None: + try: + normalized_email = normalize_email(email) + except UserError: + return None + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, username, email, password_hash, admin, approved, " + "email_verified, created_at " + "FROM users WHERE email=%s", (normalized_email,), + ) + return _user_row(cursor.fetchone()) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取用户数据") from exc + finally: + connection.close() + + def get_by_id(self, user_id: int) -> dict[str, Any] | None: + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + return None + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, username, email, password_hash, admin, approved, " + "email_verified, created_at " + "FROM users WHERE id=%s", (user_id,), + ) + return _user_row(cursor.fetchone()) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取用户数据") from exc + finally: + connection.close() + + def create_initial_user(self, username: str, password: str, + email: str | None = None, *, now: int | None = None) -> dict[str, Any]: + """Insert the first account as a regular user, never as admin. + + The setup-token file lock held by DatabasePanelState serializes this + check/insert across web workers on the same panel server. + """ + username = _validate_username(username) + password_hash = hash_password(_validate_password(password)) + email = normalize_email(email) if email is not None else None + timestamp = _validate_clock(now) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("SELECT id FROM users LIMIT 1 FOR UPDATE") + if cursor.fetchone() is not None: + raise UserError("初始用户已创建", 409) + cursor.execute( + "INSERT INTO users (username, email, password_hash, admin, " + "approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 1, 1, %s)", + (username, email, password_hash, timestamp), + ) + user_id = cursor.lastrowid + connection.commit() + return { + "id": user_id, "username": username, "email": email, + "password_hash": password_hash, "admin": False, "approved": True, + "email_verified": True, "created_at": timestamp, + } + except UserError: + connection.rollback() + raise + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + raise UserError("用户名或邮箱已存在", 409) from exc + raise DatabaseError("无法创建初始用户") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法创建初始用户") from exc + finally: + connection.close() + + def issue_registration_code(self, email: str, code: str, *, now: int | None = None, + ttl_seconds: int = 600, + cooldown_seconds: int = 60) -> bool: + """Store a code and enforce resend cooldown; False means email already used. + + The caller should return the same public response for existing and new + email addresses, and send email only when this method returns True. + """ + email = normalize_email(email) + if not isinstance(code, str) or not _CODE.fullmatch(code): + raise ValueError("Invalid registration code") + if (isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, int) + or not 60 <= ttl_seconds <= 3600 + or isinstance(cooldown_seconds, bool) or not isinstance(cooldown_seconds, int) + or not 1 <= cooldown_seconds <= ttl_seconds): + raise ValueError("Invalid code lifetime or cooldown") + timestamp = _validate_clock(now) + digest = self._code_digest(email, code) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("SELECT id FROM users WHERE email=%s", (email,)) + if cursor.fetchone() is not None: + connection.rollback() + return False + cursor.execute( + "SELECT sent_at FROM registration_codes WHERE email=%s FOR UPDATE", + (email,), + ) + existing = cursor.fetchone() + if existing is not None and timestamp - int(existing["sent_at"]) < cooldown_seconds: + raise UserError("验证码发送过于频繁,请稍后重试", 429) + if existing is None: + cursor.execute( + "INSERT INTO registration_codes " + "(email, code_hash, sent_at, expires_at, failed_attempts) " + "VALUES (%s, %s, %s, %s, 0)", + (email, digest, timestamp, timestamp + ttl_seconds), + ) + else: + cursor.execute( + "UPDATE registration_codes SET code_hash=%s, sent_at=%s, " + "expires_at=%s, failed_attempts=0 WHERE email=%s", + (digest, timestamp, timestamp + ttl_seconds, email), + ) + connection.commit() + return True + except UserError: + connection.rollback() + raise + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + raise UserError("验证码发送过于频繁,请稍后重试", 429) from exc + raise DatabaseError("无法保存注册验证码") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法保存注册验证码") from exc + finally: + connection.close() + + def revoke_registration_code(self, email: str, code: str) -> bool: + """Remove only the still-current challenge after SMTP delivery fails.""" + email = normalize_email(email) + if not isinstance(code, str) or not _CODE.fullmatch(code): + raise ValueError("Invalid registration code") + digest = self._code_digest(email, code) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT code_hash FROM registration_codes WHERE email=%s FOR UPDATE", + (email,), + ) + row = cursor.fetchone() + if row is None or not hmac.compare_digest(row["code_hash"], digest): + connection.rollback() + return False + cursor.execute( + "DELETE FROM registration_codes WHERE email=%s AND code_hash=%s", + (email, digest), + ) + connection.commit() + return True + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法撤销注册验证码") from exc + finally: + connection.close() + + def register_with_code(self, username: str, email: str, password: str, + code: str, *, now: int | None = None) -> dict[str, Any]: + username = _validate_username(username) + email = normalize_email(email) + password = _validate_password(password) + if not isinstance(code, str) or not _CODE.fullmatch(code): + raise UserError("验证码格式无效") + timestamp = _validate_clock(now) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT code_hash, expires_at, failed_attempts " + "FROM registration_codes WHERE email=%s FOR UPDATE", (email,), + ) + challenge = cursor.fetchone() + if challenge is None: + raise UserError("验证码无效或已过期") + if timestamp >= int(challenge["expires_at"]): + cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) + connection.commit() + raise UserError("验证码无效或已过期") + digest = self._code_digest(email, code) + if not hmac.compare_digest(digest, challenge["code_hash"]): + attempts = int(challenge["failed_attempts"]) + 1 + if attempts >= _MAX_CODE_ATTEMPTS: + cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) + else: + cursor.execute( + "UPDATE registration_codes SET failed_attempts=%s WHERE email=%s", + (attempts, email), + ) + connection.commit() + raise UserError("验证码无效或已过期") + password_hash = hash_password(password) + cursor.execute( + "INSERT INTO users (username, email, password_hash, admin, " + "approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 0, 1, %s)", + (username, email, password_hash, timestamp), + ) + user_id = cursor.lastrowid + cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) + connection.commit() + return { + "id": user_id, "username": username, "email": email, + "password_hash": password_hash, "admin": False, "approved": False, + "email_verified": True, "created_at": timestamp, + } + except UserError: + connection.rollback() + raise + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + raise UserError("用户名或邮箱已存在", 409) from exc + raise DatabaseError("无法创建用户") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法创建用户") from exc + finally: + connection.close() + + def list_pending_users(self) -> list[dict[str, Any]]: + """Return registered accounts awaiting operator approval, no hashes.""" + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, username, email, admin, approved, email_verified, " + "created_at FROM users WHERE approved=0 ORDER BY created_at ASC, id ASC" + ) + rows = cursor.fetchall() + return [{ + "id": int(row["id"]), "username": row["username"], + "email": row["email"], "admin": bool(row["admin"]), + "approved": bool(row["approved"]), + "email_verified": bool(row["email_verified"]), + "created_at": int(row["created_at"]), + } for row in rows] + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取待审核用户") from exc + finally: + connection.close() + + def approve_user(self, user_id: int) -> dict[str, Any] | None: + """Approve an account; only the admin-authorized HTTP route may call this.""" + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Invalid user ID") + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("UPDATE users SET approved=1 WHERE id=%s", (user_id,)) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法审核用户") from exc + finally: + connection.close() + return self.get_by_id(user_id) + + def assign_vm(self, host_scope: str, vm_uuid: str, user_id: int, + *, now: int | None = None) -> None: + host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Invalid user ID") + timestamp = _validate_clock(now) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "INSERT INTO vm_ownership (host_scope, vm_uuid, user_id, created_at) " + "VALUES (%s, %s, %s, %s)", + (host_scope, vm_uuid, user_id, timestamp), + ) + connection.commit() + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + if self.owner_of_vm(host_scope, vm_uuid) == user_id: + return + raise UserError("此虚拟机已归属于其他用户", 409) from exc + raise DatabaseError("无法记录虚拟机归属") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法记录虚拟机归属") from exc + finally: + connection.close() + + def owner_of_vm(self, host_scope: str, vm_uuid: str) -> int | None: + host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT user_id FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s", + (host_scope, vm_uuid), + ) + row = cursor.fetchone() + return None if row is None else int(row["user_id"]) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取虚拟机归属") from exc + finally: + connection.close() + + def owns_vm(self, host_scope: str, vm_uuid: str, user_id: int) -> bool: + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + return False + return self.owner_of_vm(host_scope, vm_uuid) == user_id + + def list_owned_vm_ids(self, host_scope: str, user_id: int) -> set[str]: + if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope): + raise ValueError("Invalid host scope") + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Invalid user ID") + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT vm_uuid FROM vm_ownership WHERE host_scope=%s AND user_id=%s", + (host_scope, user_id), + ) + return {row["vm_uuid"] for row in cursor.fetchall()} + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取虚拟机归属") from exc + finally: + connection.close() + + def delete_vm_owner(self, host_scope: str, vm_uuid: str) -> None: + host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "DELETE FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s", + (host_scope, vm_uuid), + ) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法删除虚拟机归属") from exc + finally: + connection.close() diff --git a/web/.gitignore b/web/.gitignore index 4253cded..5a1de84c 100644 --- a/web/.gitignore +++ b/web/.gitignore @@ -1,4 +1,4 @@ -vendor/ +/vendor/ .env .DS_Store .user.ini diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php new file mode 100644 index 00000000..e27e21bf --- /dev/null +++ b/web/app/Command/CloudSetup.php @@ -0,0 +1,154 @@ +getConnection(); + if (!$connection->getSchemaBuilder()->hasTable('user') || !$connection->getSchemaBuilder()->hasTable('shop')) { + throw new \RuntimeException('请先在全新业务数据库导入 web/sql/ss.sql'); + } + $connection->unprepared(self::schema('cloud.sql')); + if (!$connection->getSchemaBuilder()->hasColumn('shop', 'host_id')) { + $connection->getSchemaBuilder()->table('shop', static function ($table) { + $table->unsignedBigInteger('host_id')->nullable(); + }); + } + User::getConnectionResolver()->connection('log')->unprepared(self::schema('cloud_log.sql')); + self::exportEngineConfig(); + echo "虚拟化业务表、指标日志表与私有引擎配置已准备。未连接或修改任何宿主机。\n"; + return true; + } + + public static function exportEngineConfig(): bool + { + if (Config::get('enable_log', 'false') !== 'true') { + throw new \RuntimeException('引擎需要单独的日志数据库连接'); + } + $root = dirname(BASE_PATH); + $hmacFile = (string) Config::get('cloud_engine_hmac_file', $root . '/runtime/php/engine.hmac'); + $payloadFile = (string) Config::get('cloud_payload_key_file', $root . '/runtime/php/payload.key'); + $hmac = self::secret('cloud_engine_hmac_key', $hmacFile); + self::secret('cloud_payload_key', $payloadFile); + $dataDir = (string) Config::get('cloud_engine_data_dir', $root . '/runtime/engine'); + $target = (string) Config::get('cloud_engine_config_file', $root . '/runtime/engine.json'); + self::privateDirectory(dirname($target)); + $config = [ + 'main_database' => self::database(Config::getDbConfig()), + 'log_database' => self::database(Config::getLogDbConfig()), + 'service_secret' => $hmac, + 'data_dir' => $dataDir, + 'master_key_file' => $dataDir . '/master.key', + 'php_introspection_url' => (string) Config::get('cloud_introspection_url', 'http://127.0.0.1/api/internal/cloud/session-introspection'), + 'php_introspection_host' => (string) Config::get('cloud_introspection_host', ''), + ]; + self::privateWrite($target, json_encode($config, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES) . "\n"); + echo '已导出私有引擎配置:' . $target . "(密钥和数据库密码不输出)\n"; + return true; + } + + private static function schema(string $name): string + { + $sql = file_get_contents(BASE_PATH . '/sql/' . $name); + if ($sql === false || trim($sql) === '') { + throw new \RuntimeException('缺少虚拟化建表脚本:' . $name); + } + return $sql; + } + + private static function database(array $config): array + { + if ($config['driver'] !== 'mysql') { + throw new \RuntimeException('虚拟化引擎需要 MariaDB/MySQL 数据库'); + } + if ((string) $config['database'] === '' || (string) $config['username'] === '') { + throw new \RuntimeException('请完整配置业务和日志数据库'); + } + return array_intersect_key($config, array_flip(['host', 'port', 'database', 'username', 'password'])); + } + + private static function secret(string $configKey, string $file): string + { + $configured = trim((string) Config::get($configKey, '')); + if ($configured !== '') { + self::validateSecret($configured); + return $configured; + } + if (is_file($file)) { + $secret = trim((string) file_get_contents($file)); + self::validateSecret($secret); + return $secret; + } + self::privateDirectory(dirname($file)); + $secret = base64_encode(random_bytes(32)); + $oldMask = umask(0077); + try { + $stream = fopen($file, 'x'); + if ($stream === false) { + // Another initializer may have won; never overwrite a live key. + if (is_file($file)) { + $secret = trim((string) file_get_contents($file)); + self::validateSecret($secret); + return $secret; + } + throw new \RuntimeException('无法创建私有密钥文件'); + } + try { + if (fwrite($stream, $secret . "\n") !== strlen($secret) + 1) { + throw new \RuntimeException('私有密钥写入失败'); + } + fflush($stream); + } finally { + fclose($stream); + } + chmod($file, 0600); + } finally { + umask($oldMask); + } + return $secret; + } + + private static function validateSecret(string $secret): void + { + $decoded = base64_decode($secret, true); + if ($decoded === false || strlen($decoded) !== 32) { + throw new \RuntimeException('独立加密/签名密钥必须是 base64 编码的 32 字节随机数'); + } + } + + private static function privateDirectory(string $path): void + { + if (!is_dir($path) && !mkdir($path, 0700, true) && !is_dir($path)) { + throw new \RuntimeException('无法创建私有运行目录'); + } + } + + private static function privateWrite(string $path, string $contents): void + { + $oldMask = umask(0077); + $temporary = $path . '.' . bin2hex(random_bytes(8)) . '.tmp'; + try { + $written = file_put_contents($temporary, $contents, LOCK_EX); + if ($written !== strlen($contents) || !chmod($temporary, 0600) || !rename($temporary, $path)) { + throw new \RuntimeException('写入引擎配置失败'); + } + } finally { + if (is_file($temporary)) { + unlink($temporary); + } + umask($oldMask); + } + } +} diff --git a/web/app/Command/CloudWorker.php b/web/app/Command/CloudWorker.php new file mode 100644 index 00000000..36f43f2e --- /dev/null +++ b/web/app/Command/CloudWorker.php @@ -0,0 +1,28 @@ +tick(); + } catch (\Throwable $error) { + fwrite(STDERR, 'cloud worker temporarily unavailable: ' . get_class($error) . PHP_EOL); + if ($once) { + return 1; + } + $worked = false; + } + if (!$once && !$worked) { + usleep(1000000); + } + } while (!$once); + return 0; + } +} diff --git a/web/app/Command/XCat.php b/web/app/Command/XCat.php index 7931378d..2b40bff7 100644 --- a/web/app/Command/XCat.php +++ b/web/app/Command/XCat.php @@ -20,6 +20,9 @@ class XCat try { $result = match ((string) ($this->argv[1] ?? 'help')) { 'createAdmin' => $this->createAdmin(), + 'cloudInit' => CloudSetup::initialize(), + 'cloudExportConfig' => CloudSetup::exportEngineConfig(), + 'cloudWorker' => CloudWorker::run($this->argv) === 0, 'setTelegram' => $this->setTelegram(), 'backup' => Job::backup(), 'backupJob' => Job::backupJob(), @@ -92,6 +95,9 @@ class XCat { echo "Virt Cloud CLI\n" . " php xcat createAdmin [name]\n" + . " php xcat cloudInit\n" + . " php xcat cloudExportConfig\n" + . " php xcat cloudWorker [--once]\n" . " php xcat setTelegram\n" . " php xcat backup\n" . " php xcat backupJob\n" diff --git a/web/app/Controllers/Admin/CloudPageController.php b/web/app/Controllers/Admin/CloudPageController.php new file mode 100644 index 00000000..47383933 --- /dev/null +++ b/web/app/Controllers/Admin/CloudPageController.php @@ -0,0 +1,34 @@ +view()->display('admin/hosts/index.tpl'); + } + + public function templates($request, $response, $args) + { + return $this->view()->display('admin/cloud/templates.tpl'); + } + + public function rescue($request, $response, $args) + { + return $this->view()->display('admin/cloud/rescue.tpl'); + } + + public function instances($request, $response, $args) + { + return $this->view()->display('admin/cloud/instances.tpl'); + } + + public function orders($request, $response, $args) + { + return $this->view()->display('admin/cloud/orders.tpl'); + } +} diff --git a/web/app/Controllers/Admin/ShopController.php b/web/app/Controllers/Admin/ShopController.php index cde3ca9d..d64cb8c1 100644 --- a/web/app/Controllers/Admin/ShopController.php +++ b/web/app/Controllers/Admin/ShopController.php @@ -14,7 +14,7 @@ class ShopController extends AdminController { public function index($request, $response, $args) { - $columns = ['op' => '操作', 'id' => 'ID', 'name' => '套餐名称', + $columns = ['op' => '操作', 'id' => 'ID', 'name' => '套餐名称', 'host_id' => '宿主机 ID', 'cpu_cores' => 'CPU 核数', 'memory_mib' => '内存 MiB', 'bandwidth_mbps' => '带宽 Mbps', 'disk_gib' => '磁盘 GiB', 'price' => '价格', 'status' => '状态', 'stock' => '库存', 'sort' => '排序']; @@ -60,11 +60,15 @@ class ShopController extends AdminController } try { $input = []; - foreach (['name', 'price', 'cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'status', 'stock', 'sort'] as $field) { + foreach (['name', 'host_id', 'price', 'cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'status', 'stock', 'sort'] as $field) { $default = $shop->exists ? $shop->$field : null; $input[$field] = $request->getParam($field, $default); } - foreach (Shop::validatePlan($input) as $field => $value) { + $values = Shop::validatePlan($input); + if ($values['host_id'] !== null && !\App\Models\CloudHost::where('id', $values['host_id'])->where('enabled', 1)->exists()) { + throw new \InvalidArgumentException('宿主机不存在或已禁用'); + } + foreach ($values as $field => $value) { $shop->$field = $value; } if (!$shop->save()) { @@ -98,7 +102,7 @@ class ShopController extends AdminController public function ajax_shop($request, $response, $args) { $table = new Datatables(new DatatablesHelper()); - $table->query('SELECT id AS op,id,name,cpu_cores,memory_mib,bandwidth_mbps,disk_gib,price,status,stock,sort FROM shop'); + $table->query('SELECT id AS op,id,name,host_id,cpu_cores,memory_mib,bandwidth_mbps,disk_gib,price,status,stock,sort FROM shop'); $table->edit('op', static function ($data) { if (!AdminPermission::isSuperAdmin()) { return '只读'; diff --git a/web/app/Controllers/AuthController.php b/web/app/Controllers/AuthController.php index 583e1f3a..21d1c533 100644 --- a/web/app/Controllers/AuthController.php +++ b/web/app/Controllers/AuthController.php @@ -376,20 +376,19 @@ class AuthController extends BaseController Cookie::startSession(); $captch = $request->getParam('captch'); // $data = $request->post('sdf'); - $email = $request->getParam('email'); - $email = strtolower($email); + $email = $request->getParam('email'); $passwd = $request->getParam('passwd'); + if (!is_string($email) || !is_string($passwd) || strlen($email) > 254 || strlen($passwd) > 72) { + return $response->withJson(['ret' => 0, 'msg' => '邮箱或密码格式无效'], 400); + } + $email = strtolower(trim($email)); $code = $request->getParam('code'); $emailcode = $request->getParam('emailcode'); $gacode = $request->getParam('gacode'); $clientIp = $this->getLoginClientIp(); $deviceId = $this->getLoginDeviceId(); $loginEmailVerifyEnabled = $this->isLoginEmailVerifyEnabled(); - if ($loginEmailVerifyEnabled || CaptchaConfig::get('captch_login') == 'true') { - $redis = new RedisClient(); - } else { - $redis = null; - } + $redis = new RedisClient(); if ($this->isLoginIpForbidden($clientIp)) { $rs['ret'] = 0; if ($this->language == 'true') { @@ -409,20 +408,25 @@ class AuthController extends BaseController } unset($_SESSION['captch']); } + if ($this->isLoginVerifyPasswordLimited($redis, $email, $clientIp)) { + return $response->withJson(['ret' => 0, 'msg' => '尝试次数过多,请稍后再试'], 429); + } // Handle Login $user = User::where('email', '=', $email)->first(); if ($user == null) { + $this->recordLoginVerifyPasswordFail($redis, $email, $clientIp); $rs['ret'] = 0; if ($this->language == 'true') { - $rs['msg'] = "Email is not registered"; + $rs['msg'] = "Email or password is wrong"; } else { - $rs['msg'] = "邮箱未注册"; + $rs['msg'] = "邮箱或密码错误"; } return $response->getBody()->write(json_encode($rs)); } if (!Hash::checkPassword($user->pass, $passwd)) { + $this->recordLoginVerifyPasswordFail($redis, $email, $clientIp); $rs['ret'] = 0; if ($this->language == 'true') { $rs['msg'] = "Password is wrong"; @@ -449,6 +453,8 @@ class AuthController extends BaseController return $this->echoJson($response, ['ret' => 0, 'msg' => '账户已停用']); } + $this->clearLoginVerifyPasswordFail($redis, $email, $clientIp); + $loginVerifyMethod = $this->loginVerifyMethod($user); $loginSecurityRequired = $loginEmailVerifyEnabled || $loginVerifyMethod === 'ga'; if ($loginSecurityRequired && $redis === null) { diff --git a/web/app/Controllers/CloudAdminController.php b/web/app/Controllers/CloudAdminController.php new file mode 100644 index 00000000..630adb20 --- /dev/null +++ b/web/app/Controllers/CloudAdminController.php @@ -0,0 +1,173 @@ +getAttribute('cloud_actor') ?? CloudAccess::actor(); + if (!$actor['is_admin']) { + throw new CloudError('需要管理员权限', 403); + } + if ($write) { + CloudAccess::manage($actor); + } + return $actor; + } + + private function host($id): CloudHost + { + $host = CloudHost::find($id); + if ($host === null) { + throw new CloudError('宿主机不存在', 404); + } + return $host; + } + + public function scan($request, $response) + { + $actor = $this->actor($request, true); + $body = CloudInput::object($request); + CloudInput::only($body, ['host', 'port']); + return $response->withJson((new CloudEngineClient())->request('POST', '/internal/v1/hosts/scan', $actor, $body)); + } + + public function hosts($request, $response, $args = []) + { + $write = $request->getMethod() !== 'GET'; + $actor = $this->actor($request, $write); + $engine = new CloudEngineClient(); + if (!$write && !isset($args['id'])) { + return $response->withJson(['hosts' => CloudHost::orderBy('id')->get()->toArray()]); + } + if (!$write) { + $host = $this->host($args['id']); + return $response->withJson(array_merge($host->toArray(), $engine->host((int) $host->id, 'GET', 'host', $actor))); + } + $body = CloudInput::object($request, 131072); + CloudInput::only($body, ['name', 'enabled', 'host', 'port', 'private_key', 'private_key_passphrase', 'host_key', + 'confirmed_fingerprint', 'storage_pool', 'iso_pool', 'rescue_iso_pool', 'default_network', 'region', + 'public_pool_cidr', 'public_gateway', 'public_dns_servers', 'public_reserved_ips', 'public_vm_prefix']); + $name = $body['name'] ?? ''; + if (!is_string($name) || trim($name) === '' || mb_strlen($name) > 80) { + throw new CloudError('宿主机名称需为 1 至 80 字符'); + } + $enabled = filter_var($body['enabled'] ?? true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + if ($enabled === null) { + throw new CloudError('启用状态无效'); + } + unset($body['name'], $body['enabled']); + $host = isset($args['id']) ? $this->host($args['id']) : new CloudHost(); + if (!$host->exists) { + $host->name = trim($name); + $host->region = ''; + $host->enabled = false; + $host->default_network = 'default'; + $host->created_at = $host->updated_at = time(); + $host->save(); + } + // Secrets only transit this request. They are exclusively encrypted/stored by the engine. + $result = $engine->host((int) $host->id, 'PUT', 'host', $actor, $body); + $host->name = trim($name); + $host->region = (string) ($result['region'] ?? $body['region'] ?? ''); + $host->default_network = (string) ($result['default_network'] ?? $body['default_network'] ?? 'default'); + $host->enabled = $enabled; + $host->updated_at = time(); + $host->save(); + return $response->withJson(array_merge($result, $host->toArray()), isset($args['id']) ? 200 : 201); + } + + public function test($request, $response, $args) + { + $actor = $this->actor($request, true); + $this->host($args['id']); + $body = CloudInput::object($request, 131072); + return $response->withJson((new CloudEngineClient())->host((int) $args['id'], 'POST', 'host/test', $actor, $body)); + } + + public function templates($request, $response, $args = []) + { + $method = $request->getMethod(); + $actor = $this->actor($request, $method !== 'GET'); + $body = in_array($method, ['POST', 'PATCH', 'PUT'], true) ? CloudInput::object($request) : null; + $query = $request->getQueryParams(); + $hostId = filter_var($query['host_id'] ?? $body['host_id'] ?? null, FILTER_VALIDATE_INT); + if (!$hostId) { + throw new CloudError('请选择宿主机'); + } + $this->host($hostId); + if ($body !== null) { + unset($body['host_id']); + } + $kind = $args['kind']; + $resource = $kind === 'cloud' ? 'vm-templates' : 'rescue-templates'; + if (isset($args['id'])) { + $resource .= '/' . rawurlencode($args['id']); + } elseif ($kind === 'cloud' && $method === 'POST') { + $resource .= '/import'; + } + if (isset($args['job_id'])) { + $resource .= '/import-jobs/' . rawurlencode($args['job_id']); + } + return $response->withJson((new CloudEngineClient())->host($hostId, $method, $resource, $actor, $body)); + } + + public function rescueUpload($request, $response) + { + $actor = $this->actor($request, true); + $query = $request->getQueryParams(); + $hostId = filter_var($query['host_id'] ?? null, FILTER_VALIDATE_INT); + $name = $query['name'] ?? ''; + if (!$hostId || !is_string($name) || trim($name) === '' || mb_strlen($name) > 64) { + throw new CloudError('请选择宿主机并填写救援模板名称'); + } + $this->host($hostId); + if (strtolower(trim(explode(';', $request->getHeaderLine('Content-Type'))[0])) !== 'application/octet-stream') { + throw new CloudError('请直接上传 ISO 文件内容'); + } + $temporary = tempnam(sys_get_temp_dir(), 'cloud-rescue-'); + if ($temporary === false) { + throw new CloudError('无法准备私有上传文件', 503); + } + chmod($temporary, 0600); + $file = fopen($temporary, 'wb'); + try { + if ($file === false) { + throw new CloudError('无法准备私有上传文件', 503); + } + $bytes = 0; + $stream = $request->getBody(); + while (!$stream->eof()) { + $chunk = $stream->read(1048576); + $bytes += strlen($chunk); + if ($bytes > 8 * 1024 * 1024 * 1024) { + throw new CloudError('救援 ISO 超过 8 GiB', 413); + } + if ($chunk === '' && !$stream->eof()) { + throw new CloudError('上传中断'); + } + if (fwrite($file, $chunk) !== strlen($chunk)) { + throw new CloudError('无法保存上传文件', 503); + } + } + fclose($file); + $file = null; + if ($bytes < 32768) { + throw new CloudError('ISO 文件内容无效'); + } + return $response->withJson((new CloudEngineClient())->upload('/internal/v1/hosts/' . $hostId + . '/rescue-templates?name=' . rawurlencode(trim($name)), $actor, $temporary), 202); + } finally { + if (is_resource($file)) { + fclose($file); + } + unlink($temporary); + } + } +} diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php new file mode 100644 index 00000000..86448d93 --- /dev/null +++ b/web/app/Controllers/CloudApiController.php @@ -0,0 +1,297 @@ +getAttribute('cloud_actor') ?? CloudAccess::actor(); + } + + private function json($response, array $value, int $status = 200) + { + return $response->withJson($value, $status)->withHeader('Cache-Control', 'no-store'); + } + + public function session($request, $response) + { + try { + $actor = CloudAccess::actor(); + $user = Auth::getUser(); + return $this->json($response, ['authenticated' => true, 'username' => $user->user_name, + 'email' => $user->email, 'admin' => $actor['is_admin'], 'can_manage' => $actor['can_manage'], + 'approved' => true, 'csrf_token' => AdminCsrf::token(), 'balance' => (string) $user->money]); + } catch (CloudError $error) { + return $this->json($response, ['authenticated' => false, 'detail' => $error->getMessage()], $error->httpStatus === 401 ? 200 : $error->httpStatus); + } + } + + public function plans($request, $response) + { + $plans = []; + foreach (Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get() as $plan) { + $host = CloudHost::where('id', $plan->host_id)->where('enabled', 1)->first(); + if ($host !== null) { + $plans[] = ['id' => (int) $plan->id, 'name' => $plan->name, 'price' => (string) $plan->price, + 'cpu_cores' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib, + 'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'disk_gib' => (int) $plan->disk_gib, + 'stock' => (int) $plan->stock, 'host_id' => (int) $host->id, 'host_name' => $host->name, 'region' => $host->region]; + } + } + return $this->json($response, ['plans' => $plans]); + } + + public function orders($request, $response) + { + $actor = $this->actor($request); + if ($request->getMethod() === 'POST') { + $order = CloudOrderService::purchase(CloudInput::object($request), $actor); + $display = CloudOrderService::display($order); + return $this->json($response, ['order' => $display, 'job_id' => $display['job_id'], + 'status_url' => '/api/v1/jobs/' . $display['job_id']], 202); + } + $query = CloudOrder::query(); + if (!$actor['is_admin']) { + $query->where('user_id', $actor['user_id']); + } + return $this->json($response, ['orders' => $query->orderByDesc('id')->limit(200)->get()->map( + fn ($order) => CloudOrderService::display($order))->all()]); + } + + public function order($request, $response, $args) + { + $actor = $this->actor($request); + $query = CloudOrder::where('id', $args['id']); + if (!$actor['is_admin']) { + $query->where('user_id', $actor['user_id']); + } + $order = $query->first(); + if ($order === null) { + throw new CloudError('订单不存在', 404); + } + return $this->json($response, ['order' => CloudOrderService::display($order)]); + } + + public function job($request, $response, $args) + { + $actor = $this->actor($request); + $query = CloudJob::where('id', $args['id']); + if (!$actor['is_admin']) { + $query->where('user_id', $actor['user_id']); + } + $job = $query->first(); + if ($job === null) { + throw new CloudError('任务不存在', 404); + } + return $this->json($response, CloudJobService::display($job)); + } + + private function vmData(CloudInstance $instance, array $actor): array + { + $spec = json_decode($instance->spec_json, true) ?: []; + try { + $vm = (new CloudEngineClient())->host((int) $instance->host_id, 'GET', 'vms/' . rawurlencode($instance->uuid), $actor); + } catch (CloudError $error) { + $vm = ['name' => $instance->name, 'state' => 'unknown', 'detail' => '宿主机暂时无法连接']; + } + $host = CloudHost::find($instance->host_id); + return array_merge(CloudInput::safeResult($spec), CloudInput::safeResult($vm), ['id' => (string) $instance->id, 'uuid' => $instance->uuid, + 'user_id' => (int) $instance->user_id, 'owner_user_id' => (int) $instance->user_id, + 'display_uuid' => $instance->uuid, 'host_id' => (int) $instance->host_id, 'region' => $host?->region ?? '', + 'created_at' => gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at), + 'has_initial_root_password' => $instance->credential_cipher !== null]); + } + + public function vms($request, $response) + { + $actor = $this->actor($request); + $query = CloudInstance::where('status', '<>', 'deleted'); + if (!$actor['is_admin']) { + $query->where('user_id', $actor['user_id']); + } + return $this->json($response, ['vms' => $query->orderByDesc('id')->limit(200)->get()->map( + fn ($instance) => $this->vmData($instance, $actor))->all()]); + } + + public function vm($request, $response, $args) + { + $actor = $this->actor($request); + return $this->json($response, $this->vmData(CloudAccess::instance($args['id'], $actor), $actor)); + } + + public function metrics($request, $response, $args) + { + $actor = $this->actor($request); + $instance = CloudAccess::instance($args['id'], $actor); + $query = $request->getQueryParams(); + $range = $query['range'] ?? '1h'; + if (!in_array($range, ['1h', '24h', '7d', '30d'], true)) { + throw new CloudError('指标时间范围无效'); + } + $suffix = '?range=' . rawurlencode($range); + return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id, 'GET', + 'vms/' . rawurlencode($instance->uuid) . '/metrics' . $suffix, $actor)); + } + + public function credential($request, $response, $args) + { + $instance = CloudAccess::instance($args['id'], $this->actor($request), true); + if ($instance->credential_cipher === null) { + throw new CloudError('该虚拟机没有面板保存的初始密码', 404); + } + return $this->json($response, CloudSecrets::decrypt($instance->credential_cipher)); + } + + public function consoleTicket($request, $response, $args) + { + $actor = $this->actor($request); + $instance = CloudAccess::instance($args['id'], $actor, true); + $actor = CloudAccess::vmActor($instance, $actor); + return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id, 'POST', + 'vms/' . rawurlencode($instance->uuid) . '/console-ticket', $actor, [])); + } + + public function actions($request, $response, $args) + { + $actor = $this->actor($request); + $instance = CloudAccess::instance($args['id'], $actor, true); + $actor = CloudAccess::vmActor($instance, $actor); + $body = CloudInput::object($request); + CloudInput::only($body, ['action']); + if (!in_array($body['action'] ?? '', ['start', 'shutdown', 'reboot', 'poweroff', 'reset'], true)) { + throw new CloudError('操作无效'); + } + $job = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', $body); + return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $job->id], 202); + } + + public function reinstall($request, $response, $args) + { + $actor = $this->actor($request); + $instance = CloudAccess::instance($args['id'], $actor, true); + $body = CloudInput::object($request); + CloudInput::only($body, ['template_id', 'ssh_key_id', 'root_password', 'confirmation_name']); + if (($body['confirmation_name'] ?? '') !== $instance->name) { + throw new CloudError('请填写虚拟机名称确认重装'); + } + $body['template_id'] = CloudInput::template($body['template_id'] ?? null); + $key = CloudSSHKeys::owned($body['ssh_key_id'] ?? null, $actor['user_id']); + unset($body['ssh_key_id']); + $body['ssh_public_key'] = $key?->public_key ?? ''; + $body['root_password'] = CloudInput::password($body['root_password'] ?? null); + $job = CloudJobService::enqueue($instance, $actor, 'reinstall', 'POST', '/reinstall', $body, + ['password' => $body['root_password'], 'login_name' => 'root', 'auth_mode' => $key ? 'password_and_key' : 'password']); + return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $job->id], 202); + } + + public function rescue($request, $response, $args) + { + $actor = $this->actor($request); + $write = $request->getMethod() !== 'GET'; + $instance = CloudAccess::instance($args['id'], $actor, $write); + $suffix = '/rescue' . ($args['rescue_action'] ?? ''); + if (!$write) { + return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id, 'GET', + 'vms/' . rawurlencode($instance->uuid) . $suffix, $actor)); + } + $body = CloudInput::object($request); + CloudInput::only($body, ['template_id', 'confirmation_name', 'ack_data_loss']); + if (($body['confirmation_name'] ?? '') !== $instance->name) { + throw new CloudError('请填写虚拟机名称确认操作'); + } + $job = CloudJobService::enqueue($instance, $actor, 'rescue', 'POST', $suffix, $body); + return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $job->id], 202); + } + + public function delete($request, $response, $args) + { + $actor = $this->actor($request); + $instance = CloudAccess::instance($args['id'], $actor, true); + $body = CloudInput::object($request); + CloudInput::only($body, ['confirmation_name', 'delete_disks']); + if (($body['confirmation_name'] ?? '') !== $instance->name) { + throw new CloudError('请填写虚拟机名称确认删除'); + } + $deleteDisks = filter_var($body['delete_disks'] ?? false, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + if ($deleteDisks === null) { + throw new CloudError('删除磁盘选项无效'); + } + $job = CloudJobService::enqueue($instance, $actor, 'delete', 'DELETE', '?delete_disks=' . ($deleteDisks ? 'true' : 'false'), []); + return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $job->id], 202); + } + + public function sshKeys($request, $response) + { + $actor = $this->actor($request); + if ($request->getMethod() === 'POST') { + $body = CloudInput::object($request); + CloudInput::only($body, ['name', 'public_key']); + $name = $body['name'] ?? ''; + if (!is_string($name) || trim($name) === '' || mb_strlen($name) > 80) { + throw new CloudError('公钥名称需为 1 至 80 字符'); + } + $parsed = CloudSSHKeys::parse($body['public_key'] ?? ''); + if (CloudSSHKey::where('user_id', $actor['user_id'])->where('fingerprint', $parsed['fingerprint'])->exists()) { + throw new CloudError('该公钥已经添加', 409); + } + $key = new CloudSSHKey(); + $key->user_id = $actor['user_id']; + $key->name = trim($name); + $key->public_key = $parsed['public_key']; + $key->fingerprint = $parsed['fingerprint']; + $key->created_at = time(); + $key->save(); + return $this->json($response, ['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint], 201); + } + $keys = CloudSSHKey::where('user_id', $actor['user_id'])->orderBy('id')->get()->map(fn ($key) => + ['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint, 'created_at' => (int) $key->created_at])->all(); + return $this->json($response, ['keys' => $keys]); + } + + public function deleteKey($request, $response, $args) + { + $key = CloudSSHKeys::owned($args['id'], $this->actor($request)['user_id']); + $key->delete(); + return $this->json($response, ['deleted' => true]); + } + + public function resources($request, $response) + { + $actor = $this->actor($request); + $query = $request->getQueryParams(); + if (isset($query['vm_id'])) { + $hostId = (int) CloudAccess::instance($query['vm_id'], $actor)->host_id; + } else { + $plan = Shop::where('id', $query['plan_id'] ?? 0)->where('status', 1)->first(); + $hostId = (int) ($plan?->host_id ?? 0); + if (!CloudHost::where('id', $hostId)->where('enabled', 1)->exists()) { + throw new CloudError('套餐宿主机不可用', 404); + } + } + $engine = new CloudEngineClient(); + $value = $engine->host($hostId, 'GET', 'resources', $actor); + $templates = $engine->host($hostId, 'GET', 'vm-templates', $actor); + $rescue = $engine->host($hostId, 'GET', 'rescue-templates', $actor); + $value['templates'] = $templates['templates'] ?? []; + $value['rescue_templates'] = $rescue['templates'] ?? []; + $value['host_id'] = $hostId; + return $this->json($response, $value); + } +} diff --git a/web/app/Controllers/CloudInternalController.php b/web/app/Controllers/CloudInternalController.php new file mode 100644 index 00000000..a414731f --- /dev/null +++ b/web/app/Controllers/CloudInternalController.php @@ -0,0 +1,60 @@ + 60 + || !is_string($nonce) || preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $nonce) !== 1 + || !is_string($signature) || preg_match('/^[a-f0-9]{64}$/D', $signature) !== 1 + || !is_string($actor) || strlen($actor) > 2048 || preg_match('/^[A-Za-z0-9_-]+$/D', $actor) !== 1) { + return false; + } + $expected = hash_hmac('sha256', CloudEngineClient::canonical($method, $path, $body, $time, $nonce, $actor), $key); + return hash_equals($expected, $signature); + } + + public function introspection($request, $response) + { + try { + $body = (string) $request->getBody(); + $headers = ['timestamp' => $request->getHeaderLine('X-Cloud-Timestamp'), + 'nonce' => $request->getHeaderLine('X-Cloud-Nonce'), 'actor' => $request->getHeaderLine('X-Cloud-Actor'), + 'signature' => $request->getHeaderLine('X-Cloud-Signature')]; + if (strlen($body) > 4096 || !self::validSignature($request->getMethod(), $request->getRequestTarget(), + $body, $headers, CloudSecrets::key('engine_hmac_key'), time())) { + return $response->withJson(['active' => false], 403)->withHeader('Cache-Control', 'no-store'); + } + $redis = (new RedisClient())->getClient(); + if ((string) $redis->set('cloud-introspection-nonce:' . $headers['nonce'], '1', 'EX', 120, 'NX') !== 'OK') { + return $response->withJson(['active' => false], 403)->withHeader('Cache-Control', 'no-store'); + } + $value = json_decode($body, true); + if (!is_array($value) || !is_string($value['session_id'] ?? null) + || preg_match('/^[a-f0-9]{64}$/D', $value['session_id']) !== 1 + || !isset($value['user_id'], $value['host_id'], $value['vm_uuid'])) { + return $response->withJson(['active' => false], 400)->withHeader('Cache-Control', 'no-store'); + } + $session = \App\Models\CloudSession::find($value['session_id']); + $active = $session !== null && (int) $session->user_id === (int) $value['user_id'] + && CloudSessionService::active($value['session_id'], (int) $value['host_id'], (string) $value['vm_uuid']); + return $response->withJson(['active' => $active])->withHeader('Cache-Control', 'no-store'); + } catch (\Throwable $error) { + error_log('Cloud session introspection unavailable: ' . get_class($error) . ' at ' + . basename($error->getFile()) . ':' . $error->getLine() . ' ' . json_encode(array_map( + fn ($frame) => [basename($frame['file'] ?? ''), $frame['line'] ?? 0, $frame['function'] ?? ''], + array_slice($error->getTrace(), 0, 4)))); + return $response->withJson(['active' => false], 503)->withHeader('Cache-Control', 'no-store'); + } + } +} diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php new file mode 100644 index 00000000..e0a6e25c --- /dev/null +++ b/web/app/Controllers/CloudPageController.php @@ -0,0 +1,15 @@ +getBody()->write(View::getSmarty('venix')->fetch('cloud/index.tpl')); + return $response; + } +} diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php new file mode 100644 index 00000000..5da1901a --- /dev/null +++ b/web/app/Middleware/CloudApi.php @@ -0,0 +1,31 @@ +getMethod())) { + if ($request->getHeaderLine('X-CSRF-Token') !== '') { + $request = $request->withHeader(AdminCsrf::HEADER_NAME, $request->getHeaderLine('X-CSRF-Token')); + } + if (!AdminCsrf::verify($request)) { + throw new CloudError('CSRF 校验失败,请刷新页面', 403); + } + } + return $next($request->withAttribute('cloud_actor', $actor), $response); + } catch (CloudError $exception) { + return $response->withJson(['error' => $exception->getMessage(), 'detail' => $exception->getMessage()], $exception->httpStatus) + ->withHeader('Cache-Control', 'no-store'); + } catch (\Throwable $exception) { + error_log('Cloud API unavailable: ' . get_class($exception)); + return $response->withJson(['error' => '虚拟化业务暂不可用'], 503)->withHeader('Cache-Control', 'no-store'); + } + } +} diff --git a/web/app/Models/CloudHost.php b/web/app/Models/CloudHost.php new file mode 100644 index 00000000..6d1d9acc --- /dev/null +++ b/web/app/Models/CloudHost.php @@ -0,0 +1,8 @@ + 'boolean']; +} diff --git a/web/app/Models/CloudInstance.php b/web/app/Models/CloudInstance.php new file mode 100644 index 00000000..72767a78 --- /dev/null +++ b/web/app/Models/CloudInstance.php @@ -0,0 +1,8 @@ + 'decimal:2']; + protected $hidden = ['request_hash']; +} diff --git a/web/app/Models/CloudSSHKey.php b/web/app/Models/CloudSSHKey.php new file mode 100644 index 00000000..db889c73 --- /dev/null +++ b/web/app/Models/CloudSSHKey.php @@ -0,0 +1,7 @@ + 'int', 'cpu_cores' => 'int', 'memory_mib' => 'int', 'bandwidth_mbps' => 'int', 'disk_gib' => 'int', 'status' => 'int', 'stock' => 'int', 'sort' => 'int', 'price' => 'decimal:2', @@ -26,6 +27,16 @@ class Shop extends Model throw new \InvalidArgumentException('套餐名称需为 1 至 128 个字符'); } $data = ['name' => $name]; + $host = $input['host_id'] ?? null; + if ($host === null || $host === '') { + $data['host_id'] = null; + } else { + $host = filter_var($host, FILTER_VALIDATE_INT); + if ($host === false || $host < 1) { + throw new \InvalidArgumentException('请选择有效的宿主机'); + } + $data['host_id'] = $host; + } foreach ([ 'cpu_cores' => [1, 64], 'memory_mib' => [512, 262144], 'bandwidth_mbps' => [1, 100000], 'disk_gib' => [1, 4096], diff --git a/web/app/Services/Auth.php b/web/app/Services/Auth.php index 5c13684b..517cd776 100644 --- a/web/app/Services/Auth.php +++ b/web/app/Services/Auth.php @@ -28,6 +28,7 @@ class Auth public static function logout() { + \App\Services\Cloud\CloudSessionService::revokeCurrent(); self::getDriver()->logout(); } diff --git a/web/app/Services/Cloud/CloudAccess.php b/web/app/Services/Cloud/CloudAccess.php new file mode 100644 index 00000000..cefd422c --- /dev/null +++ b/web/app/Services/Cloud/CloudAccess.php @@ -0,0 +1,58 @@ +isLogin || (int) $user->enable !== 1) { + throw new CloudError('请先登录', 401); + } + $admin = (bool) $user->is_admin; + $manage = $admin && AdminPermission::isSuperAdmin(); + return ['user_id' => (int) $user->id, 'is_admin' => $admin, 'is_super_admin' => $manage, + 'can_manage' => $manage, 'session_id' => $withSession ? CloudSessionService::current($user) : '']; + } + + public static function manage(array $actor): void + { + if (!($actor['is_super_admin'] ?? false) || !($actor['can_manage'] ?? false)) { + throw new CloudError('只有超级管理员可以修改全局虚拟化配置', 403); + } + } + + public static function instance($id, array $actor, bool $write = false): CloudInstance + { + $query = CloudInstance::where('status', '<>', 'deleted'); + $global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false); + if (!($actor['is_admin'] ?? false) || ($write && !$global)) { + $query->where('user_id', $actor['user_id']); + } + if (ctype_digit((string) $id)) { + $query->where('id', (int) $id); + } else { + $query->where('uuid', (string) $id); + } + $matches = $query->limit(2)->get(); + if ($matches->count() !== 1) { + throw new CloudError('虚拟机不存在或无权访问', 404); + } + return $matches->first(); + } + + public static function vmActor(CloudInstance $instance, array $actor): array + { + $global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false); + if ((int) $instance->user_id !== (int) $actor['user_id'] && !$global) { + throw new CloudError('无权修改该虚拟机', 403); + } + $actor['can_manage'] = true; + return $actor; + } +} diff --git a/web/app/Services/Cloud/CloudEngineClient.php b/web/app/Services/Cloud/CloudEngineClient.php new file mode 100644 index 00000000..39badbf8 --- /dev/null +++ b/web/app/Services/Cloud/CloudEngineClient.php @@ -0,0 +1,111 @@ +client ??= new Client(['connect_timeout' => 3, 'timeout' => 20, 'http_errors' => false, + 'allow_redirects' => false]); + } + + public static function canonical(string $method, string $path, string $body, string $timestamp, string $nonce, string $actor): string + { + return self::canonicalDigest($method, $path, hash('sha256', $body), $timestamp, $nonce, $actor); + } + + public static function canonicalDigest(string $method, string $path, string $digest, string $timestamp, string $nonce, string $actor): string + { + return strtoupper($method) . "\n" . $path . "\n" . $digest . "\n" + . $timestamp . "\n" . $nonce . "\n" . $actor; + } + + public static function headers(string $method, string $path, string $body, array $actor, ?int $now = null, ?string $nonce = null): array + { + $encoded = rtrim(strtr(base64_encode(json_encode($actor, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)), '+/', '-_'), '='); + $timestamp = (string) ($now ?? time()); + $nonce ??= bin2hex(random_bytes(16)); + return ['X-Cloud-Timestamp' => $timestamp, 'X-Cloud-Nonce' => $nonce, 'X-Cloud-Actor' => $encoded, + 'X-Cloud-Signature' => hash_hmac('sha256', self::canonical($method, $path, $body, $timestamp, $nonce, $encoded), + CloudSecrets::key('engine_hmac_key')), 'Content-Type' => 'application/json']; + } + + public function request(string $method, string $path, array $actor, ?array $payload = null): array + { + $base = $this->base($path); + $body = $payload === null ? '' : json_encode($payload === [] ? (object) [] : $payload, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + return $this->send($method, $base . $path, [ + 'headers' => self::headers($method, $path, $body, $actor), 'body' => $body, + ]); + } + + private function base(string $path): string + { + $base = rtrim((string) Config::get('cloud_engine_url', 'http://127.0.0.1:8000'), '/'); + $url = parse_url($base); + if (!is_array($url) || ($url['scheme'] ?? '') !== 'http' + || !in_array($url['host'] ?? '', ['127.0.0.1', '[::1]', '::1'], true) + || isset($url['user']) || isset($url['pass']) || isset($url['query']) || isset($url['fragment']) + || (($url['path'] ?? '') !== '' && ($url['path'] ?? '') !== '/') + || !str_starts_with($path, '/internal/v1/') || preg_match('/[\r\n\\\\]/', $path)) { + throw new CloudError('引擎地址必须为固定本机回环地址', 503); + } + return $base; + } + + private function send(string $method, string $url, array $options): array + { + try { + $response = $this->client->request($method, $url, $options + [ + 'allow_redirects' => false, 'http_errors' => false, 'proxy' => '', + ]); + } catch (\Throwable $exception) { + throw new CloudError('虚拟化引擎响应不确定,请等待任务核对', 502); + } + $result = json_decode((string) $response->getBody(), true); + if (!is_array($result)) { + throw new CloudError('虚拟化引擎响应不确定,请等待任务核对', 502); + } + if ($response->getStatusCode() >= 400) { + // Never expose engine tracebacks, host credentials or arbitrary upstream strings. + throw new CloudError('虚拟化操作未成功(引擎状态 ' . $response->getStatusCode() . ')', + $response->getStatusCode() === 404 ? 404 : 502); + } + return $result; + } + + public function upload(string $path, array $actor, string $filename): array + { + $base = $this->base($path); + $digest = hash_file('sha256', $filename); + if ($digest === false) { + throw new CloudError('上传文件无法读取', 503); + } + $headers = self::headers('POST', $path, '', $actor); + $headers['X-Cloud-Signature'] = hash_hmac('sha256', self::canonicalDigest('POST', $path, $digest, + $headers['X-Cloud-Timestamp'], $headers['X-Cloud-Nonce'], $headers['X-Cloud-Actor']), CloudSecrets::key('engine_hmac_key')); + $headers['X-Cloud-Content-SHA256'] = $digest; + $headers['Content-Type'] = 'application/octet-stream'; + $stream = fopen($filename, 'rb'); + if ($stream === false) { + throw new CloudError('上传文件无法读取', 503); + } + try { + return $this->send('POST', $base . $path, ['headers' => $headers, 'body' => $stream, 'timeout' => 900]); + } finally { + fclose($stream); + } + } + + public function host(int $hostId, string $method, string $resource, array $actor, ?array $payload = null): array + { + if ($hostId < 1) { + throw new CloudError('宿主机不存在', 404); + } + return $this->request($method, '/internal/v1/hosts/' . $hostId . '/' . $resource, $actor, $payload); + } +} diff --git a/web/app/Services/Cloud/CloudError.php b/web/app/Services/Cloud/CloudError.php new file mode 100644 index 00000000..285fd19b --- /dev/null +++ b/web/app/Services/Cloud/CloudError.php @@ -0,0 +1,10 @@ +getBody()->getSize(); + if (($length !== null && $length > $maximum) + || (int) $request->getHeaderLine('Content-Length') > $maximum) { + throw new CloudError('请求过大', 413); + } + $value = $request->getParsedBody(); + if (!is_array($value)) { + $raw = (string) $request->getBody(); + if (strlen($raw) > $maximum) { + throw new CloudError('请求过大', 413); + } + $value = json_decode($raw, true); + } + if (!is_array($value) || ($value !== [] && array_is_list($value))) { + throw new CloudError('请求应为 JSON 对象'); + } + return $value; + } + + public static function only(array $input, array $allowed): void + { + if (array_diff(array_keys($input), $allowed) !== []) { + throw new CloudError('请求包含不允许设置的字段'); + } + } + + public static function name($value): string + { + if (!is_string($value) || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/D', $value) !== 1) { + throw new CloudError('名称只能包含英文、数字、点、下划线和连字符,最多 63 字符'); + } + return $value; + } + + public static function password($value): string + { + if ($value === null || $value === '') { + return 'Aa1!' . bin2hex(random_bytes(12)); + } + if (!is_string($value) || strlen($value) < 12 || strlen($value) > 256 + || preg_match('/[\x00\r\n]/', $value) || !preg_match('/[A-Z]/', $value) + || !preg_match('/[a-z]/', $value) || !preg_match('/[0-9]/', $value) + || !preg_match('/[^A-Za-z0-9\s]/', $value)) { + throw new CloudError('虚拟机密码需为 12 至 256 字节,并包含大写、小写、数字和符号'); + } + return $value; + } + + public static function template($value): string + { + if (!is_string($value) || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $value) !== 1) { + throw new CloudError('请选择有效的云镜像模板'); + } + return $value; + } + + public static function safeResult(array $value): array + { + foreach ($value as $key => $item) { + if (preg_match('/password|secret|private.?key|passphrase|token|credential/i', (string) $key)) { + unset($value[$key]); + } elseif (is_array($item)) { + $value[$key] = self::safeResult($item); + } + } + return $value; + } +} diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php new file mode 100644 index 00000000..f0b120b4 --- /dev/null +++ b/web/app/Services/Cloud/CloudJobService.php @@ -0,0 +1,45 @@ +getConnection()->transaction(function () use ($instance, $actor, $kind, $method, $suffix, $body, $credential) { + $locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first(); + if ($locked === null || $locked->status === 'deleted') { + throw new CloudError('虚拟机不存在', 404); + } + if (CloudJob::where('instance_id', $locked->id)->whereIn('status', ['queued', 'running', 'uncertain'])->exists()) { + throw new CloudError('虚拟机已有任务,请等待完成', 409); + } + $job = new CloudJob(); + $job->operation_id = bin2hex(random_bytes(16)); + $job->instance_id = $locked->id; + $job->user_id = $actor['user_id']; + $job->host_id = $locked->host_id; + $job->kind = $kind; + $job->status = 'queued'; + $job->payload_cipher = CloudSecrets::encrypt(['method' => $method, + 'resource' => 'vms/' . rawurlencode($locked->uuid) . $suffix, 'body' => $body, + 'credential' => $credential, 'owner_id' => (int) $locked->user_id, + 'can_manage' => (bool) ($actor['can_manage'] ?? false)]); + $job->available_at = $job->created_at = $job->updated_at = time(); + $job->save(); + return $job; + }, 3); + } + + public static function display(CloudJob $job): array + { + $result = $job->result_json === null ? null : json_decode($job->result_json, true); + return ['id' => (string) $job->id, 'operation_id' => $job->operation_id, 'kind' => $job->kind, + 'status' => $job->status, 'error' => $job->error_code, + 'result' => is_array($result) ? CloudInput::safeResult($result) : null]; + } +} diff --git a/web/app/Services/Cloud/CloudMoney.php b/web/app/Services/Cloud/CloudMoney.php new file mode 100644 index 00000000..e5b358f1 --- /dev/null +++ b/web/app/Services/Cloud/CloudMoney.php @@ -0,0 +1,24 @@ + 999999999999) { + throw new CloudError('金额超出支持范围'); + } + return intdiv($cents, 100) . '.' . str_pad((string) ($cents % 100), 2, '0', STR_PAD_LEFT); + } +} diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php new file mode 100644 index 00000000..56092eef --- /dev/null +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -0,0 +1,128 @@ + 255 || str_contains($iso, "\0"))) { + throw new CloudError('请选择安装 ISO'); + } + ksort($input); + $requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('payload_key')); + return (new User())->getConnection()->transaction(function () use ($input, $actor, $planId, $source, $name, $template, $iso, $idempotency, $requestHash) { + $user = User::where('id', $actor['user_id'])->lockForUpdate()->first(); + if ($user === null || (int) $user->enable !== 1) { + throw new CloudError('账户不可用', 403); + } + if ((int) $user->restrict_balance_purchase === 1) { + throw new CloudError('账户套餐购买服务已被管理员停用', 403); + } + $existing = CloudOrder::where('user_id', $user->id)->where('idempotency_key', $idempotency)->first(); + if ($existing !== null) { + if (!hash_equals($existing->request_hash, $requestHash)) { + throw new CloudError('同一请求标识不能用于不同订单', 409); + } + return $existing; + } + $maximum = max(1, (int) \App\Services\Config::get('cloud_max_instances_per_user', 20)); + $active = CloudInstance::where('user_id', $user->id)->where('status', '<>', 'deleted')->count(); + $reserved = CloudOrder::where('user_id', $user->id)->whereIn('status', ['queued', 'running', 'uncertain'])->count(); + if ($active + $reserved >= $maximum) { + throw new CloudError('已达到账户虚拟机数量上限', 409); + } + $plan = Shop::where('id', $planId)->lockForUpdate()->first(); + if ($plan === null || (int) $plan->status !== 1 || (int) $plan->stock === 0) { + throw new CloudError('套餐不可购买或已售罄', 409); + } + $host = CloudHost::where('id', $plan->host_id)->where('enabled', 1)->first(); + if ($host === null) { + throw new CloudError('套餐对应宿主机暂不可用', 409); + } + $price = CloudMoney::cents($plan->price); + $balance = CloudMoney::cents((string) $user->money); + if ($balance < $price) { + throw new CloudError('账户余额不足', 409); + } + $payload = ['source' => $source, 'name' => $name, 'vcpu' => (int) $plan->cpu_cores, + 'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib, + 'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'network' => $host->default_network]; + $credential = null; + if ($source === 'cloud') { + $key = CloudSSHKeys::owned($input['guest_ssh_key_id'] ?? null, (int) $user->id); + $password = CloudInput::password($input['root_password'] ?? null); + $payload += ['template_id' => $template, 'guest_ssh_public_key' => $key?->public_key ?? '', + 'root_password' => $password, 'public_ip_cidr' => '', 'gateway' => '', 'dns_servers' => []]; + $credential = ['password' => $password, 'login_name' => 'root', 'auth_mode' => $key ? 'password_and_key' : 'password']; + } else { + $payload['iso'] = $iso; + } + $safeSpec = CloudInput::safeResult($payload); + $safeSpec['plan_name'] = $plan->name; + $order = new CloudOrder(); + $order->user_id = $user->id; + $order->plan_id = $plan->id; + $order->host_id = $host->id; + $order->idempotency_key = $idempotency; + $order->request_hash = $requestHash; + $order->amount = CloudMoney::decimal($price); + $order->status = 'queued'; + $order->spec_json = json_encode($safeSpec, JSON_THROW_ON_ERROR); + $order->created_at = $order->updated_at = time(); + $order->save(); + $job = new CloudJob(); + $job->operation_id = bin2hex(random_bytes(16)); + $job->order_id = $order->id; + $job->user_id = $user->id; + $job->host_id = $host->id; + $job->kind = 'create'; + $job->status = 'queued'; + $job->payload_cipher = CloudSecrets::encrypt(['method' => 'POST', 'resource' => 'vms', + 'body' => $payload, 'credential' => $credential]); + $job->available_at = $job->created_at = $job->updated_at = time(); + $job->save(); + $user->money = CloudMoney::decimal($balance - $price); + $user->save(); + if ((int) $plan->stock > 0) { + $plan->stock--; + $plan->save(); + } + return $order; + }, 3); + } + + public static function display(CloudOrder $order): array + { + return ['id' => (string) $order->id, 'user_id' => (int) $order->user_id, 'status' => $order->status, 'amount' => (string) $order->amount, + 'plan_id' => (int) $order->plan_id, 'host_id' => (int) $order->host_id, + 'instance_id' => $order->instance_id === null ? null : (string) $order->instance_id, + 'created_at' => (int) $order->created_at, 'job_id' => (string) (CloudJob::where('order_id', $order->id)->value('id') ?? '')]; + } +} diff --git a/web/app/Services/Cloud/CloudSSHKeys.php b/web/app/Services/Cloud/CloudSSHKeys.php new file mode 100644 index 00000000..0f551c4e --- /dev/null +++ b/web/app/Services/Cloud/CloudSSHKeys.php @@ -0,0 +1,43 @@ + 16384 || str_contains($publicKey, "\n")) { + throw new CloudError('请输入单行 OpenSSH 公钥,不是私钥'); + } + $raw = base64_decode($parts[1] ?? '', true); + if ($raw === false || strlen($raw) < 4) { + throw new CloudError('SSH 公钥格式无效'); + } + $size = unpack('N', substr($raw, 0, 4))[1]; + if ($size !== strlen($type) || substr($raw, 4, $size) !== $type || strlen($raw) <= 4 + $size) { + throw new CloudError('SSH 公钥格式无效'); + } + return ['public_key' => $type . ' ' . base64_encode($raw), + 'fingerprint' => 'SHA256:' . rtrim(base64_encode(hash('sha256', $raw, true)), '=')]; + } + + public static function owned($keyId, int $owner): ?CloudSSHKey + { + if ($keyId === null || $keyId === '') { + return null; + } + $id = filter_var($keyId, FILTER_VALIDATE_INT); + if ($id === false || $id < 1) { + throw new CloudError('SSH 公钥不存在', 404); + } + $key = CloudSSHKey::where('id', $id)->where('user_id', $owner)->first(); + if ($key === null) { + throw new CloudError('SSH 公钥不存在', 404); + } + return $key; + } +} diff --git a/web/app/Services/Cloud/CloudSecrets.php b/web/app/Services/Cloud/CloudSecrets.php new file mode 100644 index 00000000..2858d48c --- /dev/null +++ b/web/app/Services/Cloud/CloudSecrets.php @@ -0,0 +1,57 @@ + ['sid'], 'jwt' => ['token'], default => ['uid', 'key', 'ip', 'expire_in', 'login_session_version'], + }; + $values = []; + foreach ($names as $name) { + $values[$name] = isset($_COOKIE[$name]) && is_string($_COOKIE[$name]) ? $_COOKIE[$name] : ''; + } + return [$driver, $values, hash('sha256', json_encode([$driver, $values], JSON_THROW_ON_ERROR))]; + } + + public static function current(User $user): string + { + [$driver, $values, $fingerprint] = self::identity(); + $version = LoginSessionRevocationService::currentVersion($user); + $session = CloudSession::where('fingerprint', $fingerprint)->first(); + if ($session !== null) { + if ((int) $session->user_id !== (int) $user->id || !(bool) $session->active + || (int) $session->version !== $version || (int) $session->expires_at <= time()) { + throw new CloudError('会话已失效,请重新登录', 401); + } + return $session->id; + } + $expiry = time() + 86400; + $reference = null; + if ($driver === 'redis') { + if (($values['sid'] ?? '') === '') { + throw new CloudError('会话已失效', 401); + } + $redis = new RedisClient(); + $ttl = (int) $redis->getClient()->ttl($values['sid']); + if ($ttl <= 0) { + throw new CloudError('会话已失效', 401); + } + $expiry = time() + $ttl; + $reference = CloudSecrets::encrypt(['sid' => $values['sid']]); + } elseif ($driver === 'jwt') { + $claims = Jwt::decodeArray($values['token'] ?? ''); + $expiry = (int) ($claims->expire_time ?? 0); + } else { + $expiry = (int) ($values['expire_in'] ?? 0); + } + if ($expiry <= time()) { + throw new CloudError('会话已失效', 401); + } + $session = new CloudSession(); + $session->id = bin2hex(random_bytes(32)); + $session->user_id = $user->id; + $session->version = $version; + $session->fingerprint = $fingerprint; + $session->auth_driver = $driver; + $session->auth_reference = $reference; + $session->active = 1; + $session->expires_at = $expiry; + $session->created_at = time(); + try { + $session->save(); + } catch (\Illuminate\Database\QueryException $exception) { + // Simultaneous first requests may race on the unique cookie fingerprint. + $existing = CloudSession::where('fingerprint', $fingerprint)->first(); + if ($existing === null || !(bool) $existing->active || (int) $existing->version !== $version + || (int) $existing->user_id !== (int) $user->id || (int) $existing->expires_at <= time()) { + throw $exception; + } + return $existing->id; + } + return $session->id; + } + + public static function revokeCurrent(): void + { + if (!(new CloudSession())->getConnection()->getSchemaBuilder()->hasTable('cloud_sessions')) { + return; + } + [, , $fingerprint] = self::identity(); + CloudSession::where('fingerprint', $fingerprint)->update(['active' => 0]); + } + + public static function active(string $id, ?int $hostId = null, ?string $uuid = null): bool + { + $session = CloudSession::find($id); + if ($session === null || !(bool) $session->active || (int) $session->expires_at <= time()) { + return false; + } + $user = User::find($session->user_id); + if ($user === null || (int) $user->enable !== 1 + || (int) $session->version !== LoginSessionRevocationService::currentVersion($user)) { + return false; + } + if ($session->auth_driver === 'redis') { + $sid = CloudSecrets::decrypt((string) $session->auth_reference)['sid'] ?? ''; + $value = (new RedisClient())->get($sid); + $decoded = LoginSessionRevocationService::decodeRedisSession($value); + if ($decoded === null || (int) $decoded['uid'] !== (int) $user->id + || !LoginSessionRevocationService::snapshotMatches($decoded['version'], (int) $session->version)) { + return false; + } + } + if ($hostId !== null || $uuid !== null) { + $query = CloudInstance::where('host_id', $hostId)->where('uuid', $uuid)->where('status', '<>', 'deleted'); + $superAdmin = (bool) $user->is_admin && in_array((int) $user->id, + array_map('intval', explode(',', (string) Config::get('super_admin'))), true); + if (!$superAdmin) { + $query->where('user_id', $user->id); + } + return $query->exists(); + } + return true; + } +} diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php new file mode 100644 index 00000000..9a2c98fd --- /dev/null +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -0,0 +1,182 @@ +engine ??= new CloudEngineClient(); + } + + public static function disposition(array $operation, bool $creating): string + { + $status = $operation['status'] ?? 'uncertain'; + if ($status === 'succeeded') { + return 'succeeded'; + } + if ($status === 'failed') { + if (!$creating || ($operation['safe_to_refund'] ?? false) === true + || ($operation['result']['creation_absent'] ?? false) === true) { + return 'failed'; + } + return 'uncertain'; + } + return in_array($status, ['pending', 'running'], true) ? 'running' : 'uncertain'; + } + + public function tick(): bool + { + $job = (new CloudJob())->getConnection()->transaction(function () { + $job = CloudJob::whereIn('status', ['queued', 'running', 'uncertain']) + ->where('available_at', '<=', time())->where('lease_until', '<=', time()) + ->orderBy('id')->lockForUpdate()->first(); + if ($job === null) { + return null; + } + $job->lease_token = bin2hex(random_bytes(16)); + $job->lease_until = time() + 180; + $job->attempts++; + $job->save(); + return $job; + }, 3); + if ($job === null) { + return false; + } + try { + $payload = CloudSecrets::decrypt($job->payload_cipher); + $actor = ['user_id' => (int) $job->user_id, 'is_admin' => false, 'is_super_admin' => false, + 'can_manage' => false, 'session_id' => '', 'operation_id' => $job->operation_id]; + $user = User::find($job->user_id); + if ($user === null || (int) $user->enable !== 1) { + if ($job->dispatched_at === null) { + $this->finish($job, ['status' => 'failed', 'safe_to_refund' => true], $payload); + return true; + } + } + if ($job->kind === 'create') { + $actor['can_provision'] = true; + $actor['can_manage'] = true; + } elseif ((int) ($payload['owner_id'] ?? 0) === (int) $job->user_id) { + $actor['can_manage'] = true; + } elseif (($payload['can_manage'] ?? false) === true && $user !== null + && (bool) $user->is_admin && in_array((int) $user->id, + array_map('intval', explode(',', (string) \App\Services\Config::get('super_admin'))), true)) { + $actor['is_admin'] = $actor['is_super_admin'] = $actor['can_manage'] = true; + } + if ($job->kind !== 'create' && !$actor['can_manage'] && $job->dispatched_at === null) { + $this->finish($job, ['status' => 'failed'], $payload); + return true; + } + if ($job->dispatched_at !== null) { + // A crash after dispatch is ambiguous. Never submit a second create or refund on a 404. + $operation = $this->engine->request('GET', '/internal/v1/operations/' . $job->operation_id, $actor); + } else { + $updated = CloudJob::where('id', $job->id)->where('lease_token', $job->lease_token) + ->whereNull('dispatched_at')->update(['dispatched_at' => time(), 'status' => 'running', 'updated_at' => time()]); + if ($updated !== 1) { + return true; + } + $operation = $this->engine->host((int) $job->host_id, $payload['method'], $payload['resource'], $actor, $payload['body']); + if (isset($operation['uuid']) && !array_key_exists('result', $operation)) { + $operation = ['status' => $operation['status'] ?? 'succeeded', 'result' => $operation]; + } + } + $this->finish($job, $operation, $payload); + } catch (\Throwable $error) { + // Diagnostics deliberately contain no raw payloads, credentials or upstream tracebacks. + error_log('cloud worker job ' . $job->id . ' uncertain: ' . get_class($error)); + CloudJob::where('id', $job->id)->where('lease_token', $job->lease_token)->update([ + 'status' => 'uncertain', 'error_code' => '等待引擎核对操作结果', 'lease_until' => 0, + 'lease_token' => null, 'available_at' => time() + 30, 'updated_at' => time()]); + if ($job->order_id !== null) { + CloudOrder::where('id', $job->order_id)->whereNotIn('status', ['succeeded', 'failed']) + ->update(['status' => 'uncertain', 'updated_at' => time()]); + } + } + return true; + } + + private function finish(CloudJob $claimed, array $operation, array $payload): void + { + $status = self::disposition($operation, $claimed->kind === 'create'); + $result = $operation['result'] ?? null; + (new CloudJob())->getConnection()->transaction(function () use ($claimed, $payload, $status, $result) { + // All financial transactions acquire the wallet first, avoiding wallet/order deadlocks. + $user = User::where('id', $claimed->user_id)->lockForUpdate()->first(); + $order = $claimed->order_id === null ? null : CloudOrder::where('id', $claimed->order_id)->lockForUpdate()->first(); + $job = CloudJob::where('id', $claimed->id)->lockForUpdate()->first(); + if ($job === null || $job->lease_token !== $claimed->lease_token || in_array($job->status, ['succeeded', 'failed'], true)) { + return; + } + $safe = is_array($result) ? CloudInput::safeResult($result) : null; + if ($status === 'succeeded' && $job->kind === 'create') { + $vm = is_array($result) ? ($result['vm'] ?? $result) : []; + $uuid = $vm['uuid'] ?? ''; + if ($order === null || !is_string($uuid) + || preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $uuid) !== 1) { + throw new CloudError('引擎成功结果缺少虚拟机标识', 502); + } + $instance = CloudInstance::where('order_id', $order->id)->first() ?? new CloudInstance(); + $instance->uuid = $uuid; + $instance->host_id = $order->host_id; + $instance->user_id = $order->user_id; + $instance->order_id = $order->id; + $instance->name = $payload['body']['name']; + $instance->status = 'active'; + $instance->spec_json = $order->spec_json; + $instance->credential_cipher = isset($payload['credential']) ? CloudSecrets::encrypt($payload['credential']) : null; + $instance->created_at = $order->created_at; + $instance->updated_at = time(); + $instance->save(); + $job->instance_id = $order->instance_id = $instance->id; + $safe = $safe ?? []; + $safe['id'] = (string) $instance->id; + $safe['uuid'] = $uuid; + } elseif ($status === 'failed' && $order !== null && $order->refunded_at === null) { + if ($user === null) { + throw new CloudError('退款账户不存在', 409); + } + $user->money = CloudMoney::decimal(CloudMoney::cents((string) $user->money) + CloudMoney::cents($order->amount)); + $user->save(); + $plan = Shop::where('id', $order->plan_id)->lockForUpdate()->first(); + if ($plan !== null && (int) $plan->stock >= 0) { + $plan->stock++; + $plan->save(); + } + $order->refunded_at = time(); + } elseif ($status === 'succeeded' && $job->instance_id !== null) { + $instance = CloudInstance::where('id', $job->instance_id)->lockForUpdate()->first(); + if ($instance !== null) { + if ($job->kind === 'delete') { + $instance->status = 'deleted'; + $instance->credential_cipher = null; + } elseif ($job->kind === 'reinstall' && isset($payload['credential'])) { + $instance->credential_cipher = CloudSecrets::encrypt($payload['credential']); + } + $instance->updated_at = time(); + $instance->save(); + } + } + $job->status = $status; + $job->result_json = $safe === null ? null : json_encode($safe, JSON_THROW_ON_ERROR); + $job->error_code = $status === 'failed' ? ($order !== null ? '开通失败,订单已退款' : '虚拟机操作失败') + : ($status === 'uncertain' ? '等待引擎核对操作结果' : null); + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = time() + 15; + $job->updated_at = time(); + $job->save(); + if ($order !== null) { + $order->status = $status; + $order->updated_at = time(); + $order->save(); + } + }, 3); + } +} diff --git a/web/app/Services/Config.php b/web/app/Services/Config.php index 1852168e..0daa6597 100644 --- a/web/app/Services/Config.php +++ b/web/app/Services/Config.php @@ -32,9 +32,11 @@ class Config public static function getDbConfig() { + [$host, $port] = self::databaseAddress('db_host', 'db_port'); return [ 'driver' => self::get('db_driver'), - 'host' => self::get('db_host'), + 'host' => $host, + 'port' => $port, 'database' => self::get('db_database'), 'username' => self::get('db_username'), 'password' => self::get('db_password'), @@ -46,9 +48,11 @@ class Config public static function getLogDbConfig() { + [$host, $port] = self::databaseAddress('log_db_host', 'log_db_port'); return [ 'driver' => self::get('db_driver'), - 'host' => self::get('log_db_host'), + 'host' => $host, + 'port' => $port, 'database' => self::get('log_db_database'), 'username' => self::get('log_db_user'), 'password' => self::get('log_db_password'), @@ -56,5 +60,30 @@ class Config 'collation' => self::get('db_collation') ]; } + + private static function databaseAddress(string $hostKey, string $portKey): array + { + $defaultHost = $hostKey === 'log_db_host' ? 'localhost' : '127.0.0.1'; + $host = trim((string) self::get($hostKey, $defaultHost)); + if ($host === '') { + $host = $defaultHost; + } + $port = self::get($portKey); + // Retain existing host:port configuration, but give PDO a separate port. + if (preg_match('/^\[([^\]]+)\]:(\d+)$/D', $host, $match) === 1 + || preg_match('/^([^:]+):(\d+)$/D', $host, $match) === 1) { + $host = $match[1]; + if ($port === null || $port === '') { + $port = $match[2]; + } + } elseif (preg_match('/^\[([^\]]+)\]$/D', $host, $match) === 1) { + $host = $match[1]; + } + $port = $port === null || $port === '' ? 3306 : filter_var($port, FILTER_VALIDATE_INT); + if ($port === false || $port < 1 || $port > 65535) { + throw new \InvalidArgumentException('数据库端口必须为 1 至 65535'); + } + return [$host, (int) $port]; + } } diff --git a/web/app/Services/Mail/Smtp.php b/web/app/Services/Mail/Smtp.php index ec544317..3cc10327 100644 --- a/web/app/Services/Mail/Smtp.php +++ b/web/app/Services/Mail/Smtp.php @@ -37,9 +37,9 @@ class Smtp extends Base $mail->SMTPSecure='ssl'; $mail->SMTPOptions = array( 'ssl' => array( - 'verify_peer' => false, - 'verify_peer_name' => false, - 'allow_self_signed' => true + 'verify_peer' => true, + 'verify_peer_name' => true, + 'allow_self_signed' => false ) ); } diff --git a/web/app/Services/UserDataDeletionService.php b/web/app/Services/UserDataDeletionService.php index 6f42cb9c..c5201a99 100644 --- a/web/app/Services/UserDataDeletionService.php +++ b/web/app/Services/UserDataDeletionService.php @@ -12,6 +12,7 @@ class UserDataDeletionService ['login_ip', 'userid'], ['payback', 'userid'], ['payback', 'ref_by'], ['paylist', 'userid'], ['ss_invite_code', 'user_id'], ['ticket', 'userid'], ['user_survey_responses', 'user_id'], + ['cloud_ssh_keys', 'user_id'], ['cloud_sessions', 'user_id'], ]; private const EMAIL_REFERENCES = [ ['checkout_apply', 'email'], ['email_verify', 'email'], ['ss_password_reset', 'email'], @@ -36,6 +37,19 @@ class UserDataDeletionService foreach ($users as $user) { $ids[] = (int) $user->id; $emails[] = strtolower(trim((string) $user->email)); + } + // Account deletion must never orphan a VM or an in-flight purchase. + if ($connection->getSchemaBuilder()->hasTable('cloud_instances') + && $connection->table('cloud_instances')->whereIn('user_id', $ids) + ->where('status', '!=', 'deleted')->exists()) { + throw new \RuntimeException('用户仍有云服务器,请先删除或转交实例后再删除账户'); + } + if ($connection->getSchemaBuilder()->hasTable('cloud_orders') + && $connection->table('cloud_orders')->whereIn('user_id', $ids) + ->whereIn('status', ['pending', 'queued', 'running', 'provisioning', 'uncertain'])->exists()) { + throw new \RuntimeException('用户仍有开通中的订单,请先处理订单后再删除账户'); + } + foreach ($users as $user) { LoginSessionRevocationService::revokeUser($user); } $emails = array_values(array_unique(array_filter($emails, 'strlen'))); diff --git a/web/bootstrap.php b/web/bootstrap.php index 81714a06..2203c3fc 100644 --- a/web/bootstrap.php +++ b/web/bootstrap.php @@ -22,7 +22,11 @@ if (!defined('ORIGINAL_REMOTE_ADDR')) { define('ORIGINAL_REMOTE_ADDR', isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : ''); } -require BASE_PATH."/config/.config.php"; +$configurationFile = BASE_PATH . '/config/config.php'; +if (!is_file($configurationFile)) { + $configurationFile = BASE_PATH . '/config/.config.php'; +} +require $configurationFile; diff --git a/web/config/.config.php.example b/web/config/.config.php.example index dfd15c3e..f2e0e6a5 100644 --- a/web/config/.config.php.example +++ b/web/config/.config.php.example @@ -20,6 +20,7 @@ $System_Config['smtp_ssl'] = 'true'; #sspanel数据库 $System_Config['db_driver'] = 'mysql'; $System_Config['db_host'] = '127.0.0.1'; +$System_Config['db_port'] = 3306; $System_Config['db_database'] = 'ss'; $System_Config['db_username'] = 'root'; $System_Config['db_password'] = ''; @@ -29,9 +30,26 @@ $System_Config['db_prefix'] = ''; #log数据库设置 $System_Config['enable_log']='true'; $System_Config['log_db_host']=''; +$System_Config['log_db_port']=3306; $System_Config['log_db_database']='user_log'; $System_Config['log_db_user']='root'; $System_Config['log_db_password']=''; +#----------------------------------------虚拟化引擎------------------------------------------- +# PHP 与引擎部署在同一台面板服务器;宿主机仍通过 SSH 远程管理。 +$System_Config['cloud_engine_url'] = 'http://127.0.0.1:8000'; +# 下列两个文件由 php xcat cloudInit 生成,属于网站用户,仅网站用户可读。 +$System_Config['cloud_engine_hmac_file'] = dirname(__DIR__, 2) . '/runtime/php/engine.hmac'; +$System_Config['cloud_payload_key_file'] = dirname(__DIR__, 2) . '/runtime/php/payload.key'; +# 可选:直接填写独立的 base64 编码 32 字节随机密钥;不要使用网站 key 代替。 +$System_Config['cloud_engine_hmac_key'] = ''; +$System_Config['cloud_payload_key'] = ''; +$System_Config['cloud_engine_config_file'] = dirname(__DIR__, 2) . '/runtime/engine.json'; +$System_Config['cloud_engine_data_dir'] = dirname(__DIR__, 2) . '/runtime/engine'; +# VNC 持续检查 PHP 会话。设为面板服务器本机可访问的网站 URL,不要指向宿主机。 +$System_Config['cloud_introspection_url'] = 'http://127.0.0.1/api/internal/cloud/session-introspection'; +$System_Config['cloud_introspection_host'] = ''; +# 本轮只按套餐价格购买开通,不包含到期、续费或在线更新。 +$System_Config['cloud_max_instances_per_user'] = 20; # redis $System_Config['redis_scheme'] = 'tcp'; $System_Config['redis_host'] = '127.0.0.1'; diff --git a/web/config/routes.php b/web/config/routes.php index 094b6d98..8bca3d58 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -41,6 +41,10 @@ if (defined("DEBUG")) { $container = new Container($configuration); $renderErrorPage = function ($response, $status, $template) { + $path = parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH); + if (is_string($path) && (str_starts_with($path, '/api/v1/') || str_starts_with($path, '/api/internal/cloud/'))) { + return $response->withJson(['detail' => $status === 500 ? '服务暂时不可用' : '接口不存在或请求方法不支持'], $status); + } $newResponse = $response->withStatus($status); $newResponse->getBody()->write(View::getSmarty()->fetch($template)); return $newResponse; @@ -84,12 +88,14 @@ $app->post('/telegram_callback', 'App\Controllers\TelegramWebhookController:hand // User Center $app->group('/user', function () { - $this->get('', 'App\Controllers\UserController:index'); - $this->get('/', 'App\Controllers\UserController:index'); + $this->get('', 'App\Controllers\CloudPageController:index'); + $this->get('/', 'App\Controllers\CloudPageController:index'); + $this->get('/cloud', 'App\Controllers\CloudPageController:index'); + $this->get('/account', 'App\Controllers\UserController:index'); $this->get('/announcement', 'App\Controllers\UserController:announcement'); $this->get('/profile', 'App\Controllers\UserController:profile'); $this->get('/invite', 'App\Controllers\UserController:invite'); - $this->get('/shop', 'App\Controllers\UserController:shop'); + $this->get('/shop', 'App\Controllers\CloudPageController:index'); $this->post('/coupon_check', 'App\Controllers\UserController:CouponCheck'); $this->get('/ticket', 'App\Controllers\UserController:ticket'); $this->get('/ticket/create', 'App\Controllers\UserController:ticket_create'); @@ -148,7 +154,11 @@ $app->group('/admin', function () { $this->get('', 'App\Controllers\AdminController:index'); $this->get('/', 'App\Controllers\AdminController:index'); // Host preparation (admin only; backend integration is not enabled yet) - $this->get('/hosts', 'App\Controllers\Admin\HostController:index'); + $this->get('/hosts', 'App\Controllers\Admin\CloudPageController:hosts'); + $this->get('/cloud/templates', 'App\Controllers\Admin\CloudPageController:templates'); + $this->get('/cloud/rescue', 'App\Controllers\Admin\CloudPageController:rescue'); + $this->get('/cloud/instances', 'App\Controllers\Admin\CloudPageController:instances'); + $this->get('/cloud/orders', 'App\Controllers\Admin\CloudPageController:orders'); $this->get('/telegram', 'App\Controllers\Admin\TelegramController:index'); $this->post('/telegram/bind', 'App\Controllers\Admin\TelegramController:bind')->add(new SuperAdmin()); $this->post('/telegram/unbind', 'App\Controllers\Admin\TelegramController:unbind')->add(new SuperAdmin()); @@ -279,5 +289,6 @@ $app->get('/yipay/callback', 'App\Controllers\YipayController:callback'); $app->get('/yipay/return', 'App\Controllers\YipayController:handleReturn'); // Run Slim Routes for App +require BASE_PATH . '/config/routes_cloud.php'; $app->add(new \App\Middleware\SiteAnalytics()); $app->run(); diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php new file mode 100644 index 00000000..37364e94 --- /dev/null +++ b/web/config/routes_cloud.php @@ -0,0 +1,37 @@ +get('/api/v1/session', 'App\Controllers\CloudApiController:session'); +$app->post('/api/internal/cloud/session-introspection', 'App\Controllers\CloudInternalController:introspection'); +$app->group('/api/v1', function () { + $this->get('/plans', 'App\Controllers\CloudApiController:plans'); + $this->map(['GET', 'POST'], '/orders', 'App\Controllers\CloudApiController:orders'); + $this->get('/orders/{id:[0-9]+}', 'App\Controllers\CloudApiController:order'); + foreach (['jobs', 'reinstall-jobs', 'rescue-jobs'] as $name) { + $this->get('/' . $name . '/{id:[0-9]+}', 'App\Controllers\CloudApiController:job'); + } + $this->get('/resources', 'App\Controllers\CloudApiController:resources'); + $this->get('/vms', 'App\Controllers\CloudApiController:vms'); + $this->get('/vms/{id}', 'App\Controllers\CloudApiController:vm'); + $this->get('/vms/{id}/metrics', 'App\Controllers\CloudApiController:metrics'); + $this->post('/vms/{id}/credential', 'App\Controllers\CloudApiController:credential'); + $this->post('/vms/{id}/console-ticket', 'App\Controllers\CloudApiController:consoleTicket'); + $this->post('/vms/{id}/actions', 'App\Controllers\CloudApiController:actions'); + $this->post('/vms/{id}/reinstall', 'App\Controllers\CloudApiController:reinstall'); + $this->map(['GET', 'POST'], '/vms/{id}/rescue', 'App\Controllers\CloudApiController:rescue'); + $this->post('/vms/{id}/rescue/force-start', 'App\Controllers\CloudApiController:rescue')->setArgument('rescue_action', '/force-start'); + $this->post('/vms/{id}/rescue/exit', 'App\Controllers\CloudApiController:rescue')->setArgument('rescue_action', '/exit'); + $this->delete('/vms/{id}', 'App\Controllers\CloudApiController:delete'); + $this->map(['GET', 'POST'], '/ssh-keys', 'App\Controllers\CloudApiController:sshKeys'); + $this->delete('/ssh-keys/{id:[0-9]+}', 'App\Controllers\CloudApiController:deleteKey'); + $this->post('/admin/hosts/scan', 'App\Controllers\CloudAdminController:scan'); + $this->map(['GET', 'POST'], '/admin/hosts', 'App\Controllers\CloudAdminController:hosts'); + $this->map(['GET', 'PUT', 'PATCH'], '/admin/hosts/{id:[0-9]+}', 'App\Controllers\CloudAdminController:hosts'); + $this->post('/admin/hosts/{id:[0-9]+}/test', 'App\Controllers\CloudAdminController:test'); + foreach (['cloud' => 'cloud-templates', 'rescue' => 'rescue-templates'] as $kind => $name) { + $this->map(['GET', 'POST'], '/admin/' . $name, 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); + $this->get('/admin/' . $name . '/import-jobs/{job_id}', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); + $this->map($kind === 'cloud' ? ['PATCH'] : ['DELETE'], '/admin/' . $name . '/{id}', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); + } + $this->post('/admin/cloud-templates/import', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', 'cloud'); + $this->post('/admin/rescue-templates/upload', 'App\Controllers\CloudAdminController:rescueUpload'); +})->add(new \App\Middleware\CloudApi()); diff --git a/web/public/cloud/account.css b/web/public/cloud/account.css new file mode 100644 index 00000000..8c3830e9 --- /dev/null +++ b/web/public/cloud/account.css @@ -0,0 +1,76 @@ +/* Legacy PHP account forms mapped onto the original VM panel design tokens. + Loaded only by user/auth layouts; never by the administrator layout. */ +body.vu-body, body.venix-auth { color: #15243a; background: #f4f7fb; font-family: Inter, "PingFang SC", "Microsoft YaHei", sans-serif; } +.vu-app { min-height: 100vh; display: grid; grid-template-columns: 244px minmax(0, 1fr); } +.vu-sidebar { position: sticky; top: 0; height: 100vh; padding: 32px 15px 22px; display: flex; flex-direction: column; gap: 24px; background: #101d2c; color: #d2dce6; } +.vu-brand { display: flex; align-items: center; gap: 12px; padding: 0 12px; color: white; font-size: 22px; font-weight: 800; text-decoration: none; } +.vu-brand img { width: 34px; height: 34px; border-radius: 10px; } +.vu-nav { display: grid; gap: 5px; } +.vu-nav a, .vu-logout { display: flex; align-items: center; gap: 12px; min-height: 43px; padding: 12px 16px; color: #91a4b7; text-decoration: none; border-radius: 9px; font-size: 13px; font-weight: 650; } +.vu-nav a:hover, .vu-nav a.is-active { color: #69e0e3; background: #173c4b; } +.vu-nav i, .vu-logout i { font-size: 19px; } +.vu-logout { margin-top: auto; } .vu-mobile-logout { display: none !important; } +.vu-main { min-width: 0; padding: 32px clamp(24px, 3.3vw, 55px) 48px; } +.vu-topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 0 0 26px; flex-wrap: wrap; } +.vu-topbar h1 { font-size: 30px; margin: 8px 0 0; letter-spacing: -.8px; } +.vu-kicker { margin: 0 0 6px; color: #159da9; font-size: 11px; font-weight: 800; letter-spacing: .14em; text-transform: uppercase; } +.vu-top-actions, .vu-hero-actions, .vu-bought-actions, .vu-ticket-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } +.vu-btn, .vu-icon-btn, .auth-button { display: inline-flex; justify-content: center; align-items: center; gap: 8px; border: 1px solid transparent; border-radius: 9px; min-height: 41px; padding: 10px 17px; font-size: 13px; font-weight: 700; text-decoration: none; color: #fff; background: #0f9eaa; cursor: pointer; } +.vu-btn:hover, .auth-button:hover { background: #0b8c98; color: white; } +.vu-btn-ghost, .auth-button-secondary { color: #445368; border-color: #d7e0e8; background: white; } +.vu-btn-soft { color: #0f8f9a; background: #e7f7f8; } .vu-btn-small { min-height: 34px; font-size: 12px; padding: 7px 11px; } +.vu-body .vu-card, .vu-body [class$="-hero-main"], .vu-body [class$="-summary"], .vu-body .vu-stat, .vu-body .vu-pay-balance { background: white; border: 1px solid #e3eaf0; border-radius: 13px; padding: 25px; box-shadow: 0 5px 16px rgba(26, 45, 65, .035); min-width: 0; } +.vu-body [class$="-hero"], .vu-body [class$="-layout"] { display: grid; grid-template-columns: minmax(0, 2fr) minmax(250px, 1fr); gap: 22px; margin-bottom: 22px; } +.vu-content-stack, .vu-body [class$="-list"], .vu-body [class$="-main"], .vu-body [class$="-side"] { min-width: 0; } +.vu-card-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 14px; margin-bottom: 20px; } +.vu-card h2, .vu-card-head h2 { margin: 0; font-size: 19px; } +.vu-card-icon { color: #159da9; font-size: 24px; } +.vu-stat-grid, .vu-stats, .vu-home-grid, .vu-ticket-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 22px; } +.vu-body p { line-height: 1.7; } .vu-body .vu-muted, .vu-body [class$="-hint"], .vu-body [class$="-meta"], .vu-body [class$="-desc"] { color: #7a8798; font-size: 13px; } +.vu-form { display: grid; gap: 18px; } .vu-form-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } +.vu-field { display: flex; flex-direction: column; gap: 9px; font-size: 13px; font-weight: 700; color: #34445a; } +.vu-input, .vu-field input, .vu-field select, .vu-field textarea, .auth-field input, .auth-field select, .auth-field textarea { width: 100%; min-height: 46px; padding: 11px 13px; border: 1px solid #dce4eb; border-radius: 9px; color: #15243a; background: white; font: inherit; } +.vu-input:focus, .vu-field input:focus, .auth-field input:focus { outline: none; border-color: #35b9c0; box-shadow: 0 0 0 4px rgba(25, 179, 187, .1); } +.vu-body input:not([type="checkbox"]):not([type="radio"]):not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="image"]):not([type="file"]):not([type="range"]):not([type="color"]), .vu-body select, .vu-body textarea { width: 100%; min-height: 46px; padding: 11px 13px; border: 1px solid #dce4eb; border-radius: 9px; color: #15243a; background: white; font: inherit; } +.vu-body textarea { display: block; min-height: 160px; resize: vertical; line-height: 1.7; margin: 10px 0 18px; } +.vu-body textarea:focus, .vu-body select:focus { outline: none; border-color: #35b9c0; box-shadow: 0 0 0 4px rgba(25,179,187,.1); } +.vu-data-table { width: 100%; border-collapse: collapse; text-align: left; font-size: 13px; } .vu-data-table th, .vu-data-table td { padding: 15px 12px; border-bottom: 1px solid #e7edf2; vertical-align: middle; } .vu-data-table th { color: #8191a4; font-size: 11px; font-weight: 700; background: #fafbfd; } +.vu-table-wrap, .vu-table-scroll { overflow-x: auto; } .vu-empty-state { padding: 30px 15px; text-align: center; color: #8292a5; } +.vu-status, .vu-pill, .vu-badge { display: inline-flex; padding: 5px 10px; border-radius: 20px; background: #eaf8f4; color: #238e70; font-size: 11px; font-weight: 700; } +.vu-message { display: none; padding: 12px; margin: 14px 0; border-radius: 9px; background: #ecf8f7; color: #267d78; } .vu-message.is-visible { display: block; } .vu-message.error { background: #fff0f0; color: #bf3e48; } +.vu-ticket-message, .vu-login-log, .vu-bought-item { border-top: 1px solid #e7edf2; padding: 18px 0; overflow-wrap: anywhere; } +.vu-theme-toggle { border: 1px solid #d7e0e8; border-radius: 9px; min-width: 41px; min-height: 41px; color: #445368; background: white; } +.vu-help-bubble { border: 1px solid #d7e0e8; color: #71859a; border-radius: 50%; width: 20px; height: 20px; display: inline-flex; justify-content: center; align-items: center; font-size: 12px; } +.vu-title-with-help { display: flex; align-items: center; gap: 10px; } +.vu-modal { position: fixed; inset: 0; display: none; align-items: center; justify-content: center; padding: 20px; background: rgba(12, 26, 42, .55); z-index: 100; } .vu-modal.is-open { display: flex; } .vu-modal-panel, .vu-modal-card { width: min(100%, 500px); border-radius: 14px; background: white; padding: 28px; } .vu-modal-lock { overflow: hidden; } +.vu-modal-backdrop, .vu-pay-dialog-backdrop { position: absolute; inset: 0; } .vu-modal-panel, .vu-pay-dialog-panel { position: relative; z-index: 1; max-height: 85vh; overflow-y: auto; } .vu-modal-close { position: absolute; top: 14px; right: 14px; border: 0; background: transparent; color: #71859a; font-size: 22px; } .vu-modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 22px; } .vu-modal-mark { color: #0f9eaa; font-size: 32px; margin-bottom: 14px; } +.vu-pay-dialog { position: fixed; inset: 0; display: none; align-items: center; justify-content: center; background: rgba(12,26,42,.55); padding: 20px; z-index: 100; } .vu-pay-dialog.is-open { display: flex; } .vu-pay-dialog-panel { width: min(100%, 480px); border-radius: 14px; background: white; padding: 28px; text-align: center; } .vu-pay-qrcode { display: flex; justify-content: center; margin: 20px 0; } .vu-pay-qrcode img, .vu-pay-qrcode canvas { max-width: 100%; } .vu-pay-chain-summary { display: flex; justify-content: space-around; gap: 14px; } .vu-pay-chain-summary span, .vu-pay-address small { display: grid; gap: 6px; } .vu-pay-address code { overflow-wrap: anywhere; } .vu-pay-methods { display: flex; gap: 12px; flex-wrap: wrap; } +.vu-stat strong { display: block; margin: 12px 0; font-size: 24px; } .vu-content-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 22px; } .vu-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } .vu-body [class$="-main"] > .vu-card + .vu-card { margin-top: 22px; } .vu-current-line { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 18px; } .vu-current-line strong, .vu-current-line span { display: block; } .vu-form-message, .vu-inline-message { color: #7a8798; font-size: 13px; line-height: 1.7; } +.vu-support-message-item { display: flex; gap: 14px; border-top: 1px solid #e7edf2; padding: 22px 0; } .vu-support-message-icon { color: #159da9; font-size: 24px; } .vu-support-message-body { flex: 1; min-width: 0; } .vu-support-message-head { display: flex; flex-wrap: wrap; gap: 12px; justify-content: space-between; color: #71859a; font-size: 12px; } .vu-support-message-item.is-admin { background: #f4fafb; } +.vu-support-message-content { margin-top: 12px; line-height: 1.8; overflow-wrap: anywhere; } .vu-support-meta { display: grid; gap: 12px; } .vu-support-meta > div { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 12px 0; border-bottom: 1px solid #e7edf2; } +.vu-support-form { display: grid; gap: 18px; } .vu-support-field { display: flex; flex-direction: column; gap: 9px; font-size: 13px; font-weight: 700; color: #34445a; } .vu-support-actions { display: flex; flex-wrap: wrap; gap: 12px; } .vu-support-message-item { border: 1px solid #e3eaf0; border-radius: 13px; padding: 22px; margin-top: 16px; background: white; } .vu-support-message-body p { margin: 14px 0 0; } .vu-support-info { display: grid; gap: 14px; margin-bottom: 22px; } .vu-support-info > div { display: grid; gap: 6px; padding: 12px 0; border-bottom: 1px solid #e7edf2; } .vu-support-info span { color: #7a8798; font-size: 12px; } +.vu-survey-options { display: grid; gap: 12px; margin: 14px 0; } .vu-survey-option { padding: 16px; display: flex; align-items: center; gap: 12px; border: 1px solid #dce4eb; border-radius: 9px; background: white; color: #34445a; text-align: left; } .vu-survey-option.is-selected, .vu-survey-option[aria-pressed="true"] { border-color: #35b9c0; background: #e7f7f8; } .vu-survey-option strong { flex: 1; } .vu-survey-question h3 { font-size: 16px; } +.vu-invoice-shell { margin: 20px 0; } .vu-invoice-card { border: 1px solid #e3eaf0; border-radius: 13px; background: white; padding: 30px; } .vu-invoice-head, .vu-invoice-parties, .vu-invoice-bottom { display: flex; justify-content: space-between; gap: 24px; flex-wrap: wrap; margin-bottom: 25px; } .vu-invoice-brand img { width: 40px; } .vu-invoice-table-wrap { overflow-x: auto; } .vu-invoice-table { width: 100%; border-collapse: collapse; } .vu-invoice-table th, .vu-invoice-table td { padding: 16px 12px; border-bottom: 1px solid #e7edf2; } .vu-invoice-total { font-size: 20px; font-weight: 700; } +.vu-notify-menu { display: none; } .vu-notification.is-open .vu-notify-menu { display: block; position: absolute; right: 0; width: 320px; max-height: 440px; overflow: auto; background: white; border: 1px solid #e3eaf0; padding: 16px; border-radius: 13px; z-index: 10; } .vu-notification { position: relative; } .vu-notify-toggle { border: 1px solid #d7e0e8; background: white; border-radius: 9px; min-height: 41px; } +.venix-auth { min-height: 100vh; display: flex; flex-direction: column; } +.auth-site-nav { display: flex; justify-content: space-between; align-items: center; gap: 20px; padding: 25px 5vw; background: white; border-bottom: 1px solid #e7edf2; } +.auth-site-nav .home-brand { color: #15243a; font-weight: 800; font-size: 22px; text-decoration: none; display: flex; align-items: center; gap: 12px; } .home-brand img { width: 34px; height: 34px; border-radius: 10px; } +.auth-site-nav nav { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; } .auth-site-nav nav a, .auth-link { color: #0f8f9a; font-size: 13px; text-decoration: none; font-weight: 700; } +.auth-shell { flex: 1; display: grid; place-items: center; width: 100%; padding: 36px 20px; } +.auth-story { display: none; } .auth-subtitle { margin: -12px 0 22px; color: #7a8798; line-height: 1.7; font-size: 13px; } +.auth-panel-wrap { width: min(100%, 460px); } .auth-panel { background: white; border: 1px solid #e3eaf0; padding: 36px; border-radius: 15px; box-shadow: 0 12px 36px rgba(26,45,65,.06); } +.auth-title { font-size: 30px; letter-spacing: -.8px; margin: 0 0 25px; color: #15243a; } +.auth-form { display: flex; flex-direction: column; gap: 18px; } .auth-field { display: flex; flex-direction: column; gap: 8px; } .auth-field label { font-size: 13px; font-weight: 700; color: #34445a; } +.auth-row { display: flex; gap: 12px; align-items: flex-start; } .auth-row > * { flex: 1; min-width: 0; } .auth-row-inline button, .auth-row-inline .auth-captcha { flex: none; } +.auth-actions { display: flex; align-items: center; justify-content: space-between; gap: 14px; } .auth-button-block { width: 100%; } +.auth-message { display: none; padding: 12px; border-radius: 9px; font-size: 13px; } .auth-message.is-visible { display: block; } .auth-message.error { color: #bf3e48; background: #fff0f0; } .auth-message.success { color: #267d78; background: #ecf8f7; } +.auth-captcha { height: 46px; border-radius: 9px; cursor: pointer; } .auth-modal { position: fixed; inset: 0; display: none; align-items: center; justify-content: center; padding: 20px; background: rgba(12,26,42,.55); z-index: 100; } .auth-modal[aria-hidden="false"] { display: flex; } .auth-modal-panel { width: min(100%, 600px); max-height: 80vh; overflow-y: auto; padding: 30px; background: white; border-radius: 14px; } .auth-modal-actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 20px; } +:root[data-bs-theme="dark"] body.vu-body { background: #101b2a; color: #dbe6f1; } +:root[data-bs-theme="dark"] .vu-body .vu-card, :root[data-bs-theme="dark"] .vu-body [class$="-hero-main"], :root[data-bs-theme="dark"] .vu-body [class$="-summary"], :root[data-bs-theme="dark"] .vu-body .vu-stat, :root[data-bs-theme="dark"] .vu-body .vu-pay-balance, :root[data-bs-theme="dark"] .vu-body .vu-modal-panel, :root[data-bs-theme="dark"] .vu-body .vu-pay-dialog-panel, :root[data-bs-theme="dark"] .vu-body .vu-invoice-card { background: #16283b; border-color: #2a4058; } +:root[data-bs-theme="dark"] .vu-body .vu-input, :root[data-bs-theme="dark"] .vu-body .vu-field input, :root[data-bs-theme="dark"] .vu-body .vu-field select, :root[data-bs-theme="dark"] .vu-body .vu-field textarea { background: #102034; color: #dbe6f1; border-color: #2a4058; } +:root[data-bs-theme="dark"] .vu-body textarea, :root[data-bs-theme="dark"] .vu-body select { background: #102034; color: #dbe6f1; border-color: #2a4058; } +:root[data-bs-theme="dark"] .vu-body .vu-support-message-item { background: #16283b; border-color: #2a4058; } :root[data-bs-theme="dark"] .vu-body .vu-support-field { color: #bccde0; } +:root[data-bs-theme="dark"] .vu-body .vu-field { color: #bccde0; } :root[data-bs-theme="dark"] .vu-body .vu-data-table th { background: #102034; } :root[data-bs-theme="dark"] .vu-body .vu-data-table td, :root[data-bs-theme="dark"] .vu-body .vu-data-table th { border-color: #2a4058; } +:root[data-bs-theme="dark"] .vu-body .vu-btn-ghost, :root[data-bs-theme="dark"] .vu-body .vu-theme-toggle { background: #16283b; color: #c2d3e6; border-color: #2a4058; } +@media (max-width: 960px) { .vu-app { display: block; } .vu-sidebar { position: relative; height: auto; padding: 17px 20px; gap: 14px; } .vu-nav { display: flex; flex-wrap: wrap; gap: 5px; } .vu-nav a { padding: 8px 11px; min-height: 35px; } .vu-nav .vu-mobile-logout { display: flex !important; } .vu-logout { display: none; } .vu-main { padding: 28px 20px; } } +@media (max-width: 650px) { .vu-body [class$="-hero"], .vu-body [class$="-layout"], .vu-form-row, .vu-form-grid { grid-template-columns: 1fr; } .auth-panel { padding: 26px 20px; } .auth-row:not(.auth-row-inline) { flex-direction: column; } .auth-row:not(.auth-row-inline) > * { width: 100%; } .auth-site-nav { padding: 20px; } .auth-site-nav .home-brand { font-size: 18px; } } diff --git a/web/public/cloud/admin.css b/web/public/cloud/admin.css new file mode 100644 index 00000000..1887ce4d --- /dev/null +++ b/web/public/cloud/admin.css @@ -0,0 +1,12 @@ +/* Scoped to cloud admin page content. Never load client styles in venix. */ +.cloud-admin { margin: 24px 0; } +.cloud-admin .cloud-admin-grid { display: grid; grid-template-columns: minmax(240px, 1fr) minmax(320px, 1.5fr); gap: 24px; } +.cloud-admin .cloud-admin-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } +.cloud-admin .cloud-admin-full { grid-column: 1 / -1; } +.cloud-admin .cloud-admin-host { display: block; width: 100%; text-align: left; margin: 8px 0; } +.cloud-admin .cloud-admin-row { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; border-bottom: 1px solid #dce3ed; padding: 16px 0; } +.cloud-admin .cloud-admin-row input { flex: 1; min-width: 180px; } +.cloud-admin .cloud-admin-row .cloud-admin-meta { flex-basis: 100%; overflow-wrap: anywhere; color: #7b8795; } +.cloud-admin .cloud-admin-notice { white-space: pre-wrap; overflow-wrap: anywhere; } +.cloud-admin table td { overflow-wrap: anywhere; max-width: 300px; } +@media (max-width: 900px) { .cloud-admin .cloud-admin-grid, .cloud-admin .cloud-admin-form-grid { grid-template-columns: 1fr; } } diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js new file mode 100644 index 00000000..0a5075b5 --- /dev/null +++ b/web/public/cloud/admin.js @@ -0,0 +1,90 @@ +const root = document.querySelector('[data-cloud-admin]'); +const byId = id => document.getElementById(id); +const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], selectedHost: '', scanned: null, scanTarget: '', busy: false, epoch: 0 }; +const canManage = window.ADMIN_CAN_MANAGE === true; +const collection = (payload, key = 'items') => Array.isArray(payload) ? payload : Array.isArray(payload?.[key]) ? payload[key] : Array.isArray(payload?.items) ? payload.items : []; +function element(tag, className = '', content) { const node = document.createElement(tag); node.className = className; if (content !== undefined) node.textContent = String(content); return node; } +function notice(message, error = false) { const box = byId('cloud-admin-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`; } +function errorMessage(payload, status) { if (Array.isArray(payload?.detail)) return payload.detail.map(item => item.msg || '输入错误').join(';'); return String(payload?.detail || payload?.message || payload?.msg || `请求失败 (${status})`); } +async function api(path, options = {}) { + const method = (options.method || 'GET').toUpperCase(); const headers = new Headers({ Accept: 'application/json' }); + if (!['GET', 'HEAD'].includes(method)) { if (!canManage) throw new Error('当前管理员仅可查看,不能修改配置。'); if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) throw new Error('请通过 HTTPS 修改宿主机及镜像配置。'); headers.set('X-CSRF-Token', state.csrf); headers.set('Content-Type', options.raw ? 'application/octet-stream' : 'application/json'); } + const response = await fetch(path, { ...options, method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : options.raw ? options.body : JSON.stringify(options.body) }); + let payload = null; if (response.status !== 204) { try { payload = await response.json(); } catch { throw new Error('服务返回非 JSON 响应,请检查 PHP 和反代配置。'); } } + if (response.status === 401) { location.assign('/auth/login'); throw new Error('登录已过期。'); } + if (!response.ok || payload?.ret === 0) throw new Error(errorMessage(payload, response.status)); return payload; +} +function formList(value) { return String(value || '').split(/[\s,]+/).filter(Boolean); } +function profile(host) { return { ...host, ...(host.profile || host.config || {}) }; } +async function loadHosts() { state.hosts = collection(await api('/api/v1/admin/hosts'), 'hosts').map(profile); return state.hosts; } +function resetScan() { state.scanned = null; state.scanTarget = ''; if (byId('host-fingerprint')) byId('host-fingerprint').textContent = ''; if (byId('host-fingerprint-confirm')) byId('host-fingerprint-confirm').checked = false; } +function fillHost(host) { + byId('host-form').reset(); resetScan(); const h = host || {}; byId('host-id').value = h.id || ''; byId('host-form-title').textContent = host ? `编辑宿主机 · ${h.name}` : '添加宿主机'; + const fields = { 'host-name': h.name || '', 'host-region': h.region || '', 'host-address': h.host || '', 'host-port': h.port || 22, 'host-storage-pool': h.storage_pool || '/home/kvm', 'host-iso-pool': h.iso_pool || '/home/iso', 'host-rescue-pool': h.rescue_iso_pool || '/home/rescue-iso', 'host-network': h.default_network || 'bridge:br0', 'host-public-pool': h.public_pool_cidr || '', 'host-gateway': h.public_gateway || '', 'host-dns': Array.isArray(h.public_dns_servers) ? h.public_dns_servers.join(', ') : '1.1.1.1, 8.8.8.8', 'host-reserved': Array.isArray(h.public_reserved_ips) ? h.public_reserved_ips.join(', ') : '', 'host-vm-prefix': h.public_vm_prefix || '' }; + for (const [id, value] of Object.entries(fields)) byId(id).value = value; + byId('host-private-key').value = ''; byId('host-passphrase').value = ''; byId('host-enabled').checked = h.enabled !== false; byId('host-form-error').textContent = ''; +} +function renderHosts() { + const list = byId('host-list'); list.replaceChildren(); if (!state.hosts.length) list.append(element('p', 'text-muted', '暂无宿主机。')); + for (const host of state.hosts) { const button = element('button', 'btn btn-light cloud-admin-host'); button.type = 'button'; button.append(element('strong', '', host.name || `宿主机 ${host.id}`), element('div', 'text-muted', `${host.region || '地区未设置'} · #${host.id} · ${host.enabled ? '启用' : '停用'}`)); button.addEventListener('click', async () => { if (state.busy) return; try { fillHost(profile(await api(`/api/v1/admin/hosts/${encodeURIComponent(host.id)}`))); notice('已读取配置。若需保存,请重新扫描并核对主机指纹。'); } catch (error) { notice(error.message, true); } }); list.append(button); } +} +async function scanHost() { + if (state.busy) return; const host = byId('host-address').value.trim(); const port = Number(byId('host-port').value); if (!host || port < 1 || port > 65535) return notice('请输入正确的 SSH 地址和端口。', true); + state.busy = true; byId('host-scan').disabled = true; resetScan(); notice('正在扫描 SSH 主机指纹…'); + try { const result = await api('/api/v1/admin/hosts/scan', { method: 'POST', body: { host, port } }); if (byId('host-address').value.trim() !== host || Number(byId('host-port').value) !== port) throw new Error('扫描期间地址发生变化,请重新扫描。'); if (!result.host_key || !result.fingerprint) throw new Error('扫描响应缺少主机公钥或指纹。'); state.scanned = result; state.scanTarget = `${host}:${port}`; byId('host-fingerprint').textContent = `${result.key_type || 'SSH'}\n${result.fingerprint}`; notice('请通过宿主机控制台等可信渠道核对指纹,勾选确认后再保存。'); } + catch (error) { notice(error.message, true); } finally { state.busy = false; byId('host-scan').disabled = !canManage; } +} +async function saveHost(event) { + event.preventDefault(); if (state.busy) return; + const host = byId('host-address').value.trim(); const port = Number(byId('host-port').value); const id = byId('host-id').value; + if (!state.scanned || state.scanTarget !== `${host}:${port}` || !byId('host-fingerprint-confirm').checked) return notice('请先扫描并核对 SSH 主机指纹。', true); + if (!id && !byId('host-private-key').value.trim()) return notice('首次添加必须提供现有 SSH 私钥。', true); + const body = { name: byId('host-name').value.trim(), enabled: byId('host-enabled').checked, host, port, host_key: state.scanned.host_key, confirmed_fingerprint: state.scanned.fingerprint, private_key: byId('host-private-key').value.trim(), private_key_passphrase: byId('host-passphrase').value, region: byId('host-region').value.trim(), storage_pool: byId('host-storage-pool').value.trim(), iso_pool: byId('host-iso-pool').value.trim(), rescue_iso_pool: byId('host-rescue-pool').value.trim(), default_network: byId('host-network').value.trim(), public_pool_cidr: byId('host-public-pool').value.trim(), public_gateway: byId('host-gateway').value.trim(), public_dns_servers: formList(byId('host-dns').value), public_reserved_ips: formList(byId('host-reserved').value), public_vm_prefix: byId('host-vm-prefix').value ? Number(byId('host-vm-prefix').value) : null }; + state.busy = true; byId('host-save').disabled = true; notice('正在测试连接并保存…'); + try { const result = await api(`/api/v1/admin/hosts${id ? '/' + encodeURIComponent(id) : ''}`, { method: id ? 'PUT' : 'POST', body }); await loadHosts(); renderHosts(); fillHost(result?.id ? profile(result) : null); notice('宿主机配置已保存。套餐可在“商品管理”绑定此宿主机。'); } + catch (error) { byId('host-form-error').textContent = error.message; notice(error.message, true); } + finally { delete body.private_key; delete body.private_key_passphrase; byId('host-private-key').value = ''; byId('host-passphrase').value = ''; state.busy = false; byId('host-save').disabled = !canManage; } +} +function catalogPath() { return root.dataset.cloudAdmin === 'rescue' ? '/api/v1/admin/rescue-templates' : '/api/v1/admin/cloud-templates'; } +async function loadCatalog() { + const hostId = byId('catalog-host').value; state.selectedHost = hostId; const epoch = ++state.epoch; const list = byId('catalog-list'); list.replaceChildren(); if (!hostId) return list.append(element('p', 'text-muted', '请先添加宿主机。')); + notice('正在读取所选宿主机的模版…'); + try { const entries = collection(await api(`${catalogPath()}?host_id=${encodeURIComponent(hostId)}`), 'templates'); if (epoch !== state.epoch) return; + if (!entries.length) list.append(element('p', 'text-muted', '暂无模版。')); + for (const entry of entries) { const row = element('form', 'cloud-admin-row'); const name = element('input', 'form-control'); name.value = entry.name || ''; name.maxLength = 64; name.required = true; name.setAttribute('aria-label', '模版名称'); name.disabled = !canManage; const save = element('button', 'btn btn-outline-primary', '保存名称'); save.type = 'submit'; save.disabled = !canManage; const remove = element('button', 'btn btn-outline-danger', '删除'); remove.type = 'button'; remove.disabled = !canManage; row.append(name, save, remove, element('small', 'cloud-admin-meta', `${entry.os_family || '镜像'} ${entry.os_version || ''} · ${entry.size_bytes ? (entry.size_bytes / 1024 ** 3).toFixed(2) + ' GiB' : entry.id}`)); + if (root.dataset.cloudAdmin === 'rescue') { name.readOnly = true; save.hidden = true; save.disabled = true; } + row.addEventListener('submit', async event => { event.preventDefault(); if (root.dataset.cloudAdmin === 'rescue') return; save.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}`, { method: 'PATCH', body: { host_id: Number(hostId), name: name.value.trim() } }); notice('名称已保存。'); } catch (error) { notice(error.message, true); } finally { save.disabled = !canManage; } }); + remove.addEventListener('click', async () => { if (!confirm(`删除所选宿主机上的模版“${entry.name}”?正在使用的模版可能不能删除。`)) return; remove.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}`, { method: 'DELETE' }); await loadCatalog(); } catch (error) { notice(error.message, true); remove.disabled = !canManage; } }); list.append(row); + } notice(`已加载 ${entries.length} 个模版。`); + } catch (error) { notice(error.message, true); } +} +async function importProgress(result) { + if (!result?.job_id) return; + const url = result.status_url || `${catalogPath()}/import-jobs/${encodeURIComponent(result.job_id)}?host_id=${encodeURIComponent(state.selectedHost)}`; + if (!url.startsWith('/api/v1/')) throw new Error('导入状态地址无效。'); + for (let i = 0; i < 1800; i++) { const job = await api(url); notice(job.phase || `导入状态:${job.status}`); if (['succeeded', 'completed', 'done'].includes(job.status)) return; if (['failed', 'uncertain', 'cancelled'].includes(job.status)) throw new Error(job.error || '导入未完成,请核查宿主机状态后再操作。'); await new Promise(resolve => setTimeout(resolve, 2000)); } throw new Error('导入仍在进行,请稍后刷新查看。不要重复提交。'); +} +async function importTemplate(event) { + event.preventDefault(); if (state.busy) return; const hostId = byId('catalog-host').value; if (!hostId) return notice('请选择宿主机。', true); const button = byId('template-import-button'); state.busy = true; button.disabled = true; byId('catalog-host').disabled = true; + try { const result = await api('/api/v1/admin/cloud-templates/import', { method: 'POST', body: { host_id: Number(hostId), name: byId('template-name').value.trim(), url: byId('template-url').value.trim(), sha256: byId('template-sha256').value.trim() } }); await importProgress(result); await loadCatalog(); notice('镜像导入已完成。'); } + catch (error) { notice(error.message, true); } finally { state.busy = false; button.disabled = !canManage; byId('catalog-host').disabled = false; } +} +async function uploadRescue(event) { + event.preventDefault(); if (state.busy) return; const hostId = byId('catalog-host').value; const file = byId('rescue-file').files?.[0]; if (!hostId || !file) return notice('请选择宿主机和 ISO。', true); if (!file.name.toLowerCase().endsWith('.iso') || file.size > 8 * 1024 ** 3 || file.size < 32768) return notice('请选择小于 8 GiB 的有效 ISO 文件。', true); + const button = byId('rescue-upload-button'); state.busy = true; button.disabled = true; byId('catalog-host').disabled = true; notice('正在上传救援 ISO,请勿关闭页面…'); + try { const result = await api(`/api/v1/admin/rescue-templates/upload?host_id=${encodeURIComponent(hostId)}&name=${encodeURIComponent(byId('rescue-name').value.trim())}`, { method: 'POST', body: file, raw: true }); await importProgress(result); byId('rescue-file').value = ''; await loadCatalog(); notice('救援 ISO 导入已完成。'); } + catch (error) { notice(error.message, true); } finally { state.busy = false; button.disabled = !canManage; byId('catalog-host').disabled = false; } +} +async function records() { + const kind = root.dataset.cloudAdmin; notice('正在加载…'); + try { const payload = await api(`/api/v1/${kind === 'instances' ? 'vms' : 'orders'}`); const entries = collection(payload, kind === 'instances' ? 'vms' : 'orders'); const tbody = byId('admin-records'); tbody.replaceChildren(); for (const record of entries) { const row = element('tr'); const fields = kind === 'instances' ? [record.name || record.id, record.owner_email || record.user_email || record.owner_user_id || record.user_id, record.host_name || record.host_id, record.state || record.status, String(record.public_ip_cidr || '').split('/')[0], `${record.vcpu ?? record.cpu_cores ?? '—'} vCPU · ${record.memory_mib ?? '—'} MiB · ${record.disk_gib ?? '—'} GiB`] : [record.id, record.user_email || record.user_id, record.plan_name || record.plan_id, record.amount || record.price, record.status, `${record.instance_id || '—'} / ${record.job_id || '—'}`, `${record.created_at || ''}${record.error ? ' · ' + record.error : ''}`]; for (const field of fields) row.append(element('td', '', field ?? '—')); tbody.append(row); } notice(`已加载 ${entries.length} 条记录。`); } catch (error) { notice(error.message, true); } +} +async function initialize() { + if (!root) return; + try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin) throw new Error('需要管理员权限。'); if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。'); + if (root.dataset.cloudAdmin === 'hosts') { await loadHosts(); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan); if (!canManage) byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); } + else if (['templates', 'rescue'].includes(root.dataset.cloudAdmin)) { await loadHosts(); const select = byId('catalog-host'); select.replaceChildren(); for (const host of state.hosts) { const option = element('option', '', `${host.name} · ${host.region || '地区未设置'}`); option.value = String(host.id); select.append(option); } select.addEventListener('change', loadCatalog); if (byId('template-import')) byId('template-import').addEventListener('submit', importTemplate); if (byId('rescue-upload')) byId('rescue-upload').addEventListener('submit', uploadRescue); await loadCatalog(); } + else { byId('admin-records-refresh').addEventListener('click', records); await records(); } + } catch (error) { notice(error.message, true); } +} +void initialize(); diff --git a/web/public/cloud/almalinux-icon.svg b/web/public/cloud/almalinux-icon.svg new file mode 100644 index 00000000..2d3719fb --- /dev/null +++ b/web/public/cloud/almalinux-icon.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + diff --git a/web/public/cloud/app.js b/web/public/cloud/app.js new file mode 100644 index 00000000..d4fb7e86 --- /dev/null +++ b/web/public/cloud/app.js @@ -0,0 +1,742 @@ +// PHP owns authentication, authorisation, ownership and purchasing. No engine +// address, token, host credential or unrestricted create API exists in this UI. +const byId = (id) => document.getElementById(id); +const state = { csrfToken: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, view: 'list', selectedVmId: null, metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, orderPoll: null, mutationBusy: false, rescueActive: false, rescueStaged: false }; +const text = (id, value) => { byId(id).textContent = value ?? '—'; }; +const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.orders) ? payload.orders : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : []; +function showError(id, message) { text(id, message); byId(id).hidden = !message; } +let toastTimer; +function toast(message, kind = '') { const element = byId('toast'); element.textContent = message; element.className = `toast ${kind}`; element.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { element.hidden = true; }, 5000); } +async function copyText(value) { if (navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(value); return; } catch {} } const area = document.createElement('textarea'); area.value = value; area.style.position = 'fixed'; area.style.opacity = '0'; document.body.append(area); area.select(); try { if (!document.execCommand('copy')) throw new Error('浏览器无法复制,请手动选择文本。'); } finally { area.value = ''; area.remove(); } } +function requireSecureTransport() { if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) throw new Error('请通过 HTTPS 使用登录凭据和虚拟机控制功能。'); } +async function api(path, options = {}) { + const method = (options.method || 'GET').toUpperCase(); + const headers = new Headers({ Accept: 'application/json', ...options.headers }); + if (!['GET', 'HEAD'].includes(method)) { requireSecureTransport(); headers.set('X-CSRF-Token', state.csrfToken); if (options.body !== undefined) headers.set('Content-Type', 'application/json'); } + const response = await fetch(path, { ...options, method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : JSON.stringify(options.body) }); + let payload = null; + if (response.status !== 204) { try { payload = await response.json(); } catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); } } + if (response.status === 401) { clearCredential(); closeConsole(); location.assign('/auth/login'); throw new Error('登录已过期。'); } + if (!response.ok || payload?.ret === 0) { const detail = Array.isArray(payload?.detail) ? payload.detail.map(item => item.msg || '输入错误').join(';') : payload?.detail; throw new Error(String(detail || payload?.message || payload?.msg || payload?.error || `请求失败 (${response.status})`)); } + return payload; +} +function normalizeVm(vm) { return { ...vm, uuid: String(vm.uuid || vm.id || ''), api_id: String(vm.id || vm.uuid || ''), vcpu: vm.vcpu ?? vm.cpu_cores, memory_mib: vm.memory_mib, public_ip_cidr: vm.public_ip_cidr || vm.public_ip || '', password_available: vm.password_available === true || vm.has_initial_root_password === true }; } +function selectedVm() { return state.vms.find(vm => vm.uuid === state.selectedVmId); } +function vmPath(vm = selectedVm()) { if (!vm) throw new Error('请先选择虚拟机。'); return `/api/v1/vms/${encodeURIComponent(vm.api_id)}`; } +function clearCredential() { clearTimeout(state.credentialTimer); state.credentialPassword = ''; state.credentialVisible = false; text('vm-detail-root-password', '********'); byId('vm-detail-password-reveal').setAttribute('aria-pressed', 'false'); } +function showView(view) { + clearCredential(); stopVmMetrics(); state.view = view; + byId('vm-workspace').hidden = ['keys', 'orders'].includes(view); + byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('orders-workspace').hidden = view !== 'orders'; + const sections = { list: 'vm-list-view', detail: 'vm-detail-view', create: 'create-view', reinstall: 'reinstall-view', rescue: 'rescue-view' }; + for (const [name, id] of Object.entries(sections)) byId(id).hidden = view !== name; + document.querySelectorAll('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === view)); + text('breadcrumb-current', ({ list: '虚拟机', detail: '虚拟机详情', create: '购买并开通', reinstall: '重装系统', rescue: '紧急救援', keys: '公钥管理', orders: '订单' })[view]); + const hash = ({ list: '', create: 'plans', keys: 'keys', orders: 'orders' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : ''); + history.replaceState(null, '', `${location.pathname}${location.search}${hash ? '#' + hash : ''}`); + window.scrollTo({ top: 0, behavior: 'auto' }); + if (view === 'detail') startVmMetrics(); +} +async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders') { showView('orders'); await loadOrders(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } } +async function loadVms() { + if (state.loadingVMs) return; + state.loadingVMs = true; + try { state.vms = items(await api('/api/v1/vms')).map(normalizeVm); showError('cloud-page-error', ''); renderVMs(); const vm = selectedVm(); if (vm && state.view === 'detail') renderVmDetail(vm); else if (!vm && ['detail', 'reinstall', 'rescue'].includes(state.view)) showView('list'); } + catch (error) { showError('cloud-page-error', error.message); if (!state.vms.length) renderVMs(true); } + finally { state.loadingVMs = false; } +} +function openVmDetail(uuid) { const vm = state.vms.find(item => item.uuid === String(uuid)); if (!vm) return toast('虚拟机不存在,请刷新。', 'error'); state.selectedVmId = vm.uuid; renderVmDetail(vm); showView('detail'); clearVmMetrics('正在加载监控数据…'); } +function renderVmDetail(vm) { + text('vm-detail-name', vm.name); text('vm-detail-state', stateLabel(vm.state)); byId('vm-detail-state').className = `state-pill ${stateCategory(vm.state)}`; + for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm)); + for (const id of ['vm-detail-ip', 'vm-detail-header-ip']) text(id, vmIp(vm)); + text('vm-detail-header-created-at', vmCreatedAgo(vm)); const system = vmSystemInfo(vm); text('vm-detail-os-label', system.label); text('vm-detail-os', system.value); + text('vm-detail-spec', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`); text('vm-detail-disk', diskLabel(vm)); text('vm-detail-ssh-user', vm.login_name || (vm.os_source === 'cloud_template' ? 'root' : '未记录')); + byId('vm-detail-ip-copy').hidden = vmIp(vm) === '未获取'; + text('vm-detail-root-password', vm.password_available ? (state.credentialVisible ? state.credentialPassword : '********') : '未记录'); + for (const id of ['vm-detail-password-reveal', 'vm-detail-password-copy']) byId(id).hidden = !vm.password_available; + const running = stateCategory(vm.state) === 'running'; const stopped = stateCategory(vm.state) === 'stopped'; + const primary = byId('vm-detail-primary-actions'); const danger = byId('vm-detail-danger-actions'); primary.replaceChildren(); danger.replaceChildren(); + primary.append(actionButton('控制台', () => openConsole(vm), { disabled: !running }), actionButton('开机', () => powerAction('start'), { disabled: !stopped }), actionButton('正常关机', () => powerAction('shutdown'), { disabled: !running }), actionButton('重启', () => powerAction('reboot'), { disabled: !running })); + danger.append(actionButton('重装系统', () => openReinstall(vm), { variant: 'danger', disabled: vm.os_source !== 'cloud_template' }), actionButton('紧急救援', () => openRescue(vm), { variant: 'danger' }), actionButton('强制重置', () => powerAction('reset', true), { variant: 'danger', disabled: !running }), actionButton('强制断电', () => powerAction('poweroff', true), { variant: 'danger', disabled: stopped }), actionButton('删除虚拟机', deleteVm, { variant: 'danger', disabled: !stopped })); + if (state.mutationBusy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); +} +async function powerAction(action, dangerous = false) { if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVms(); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } +async function deleteVm() { const vm = selectedVm(); if (!vm || state.mutationBusy) return; const confirmation = prompt(`永久删除“${vm.name}”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认:`); if (confirmation === null) return; if (confirmation !== vm.name) return toast('虚拟机名称不匹配,未执行删除。', 'error'); state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true } }); toast('删除任务已提交,正在执行…'); if (result.job_id) await pollJob('delete', result.job_id); toast('虚拟机删除已完成。', 'success'); state.selectedVmId = null; showView('list'); await loadVms(); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } +function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); } +async function credential(copy = false) { + const vm = selectedVm(); if (!vm || !vm.password_available) return; + if (!copy && state.credentialVisible) return clearCredential(); + const id = vm.api_id; + try { const result = await api(`${vmPath(vm)}/credential`, { method: 'POST' }); if (selectedVm()?.api_id !== id || state.view !== 'detail') return; if (!result?.password) throw new Error('没有可查看的初始密码。'); if (copy) { await copyText(result.password); toast('初始密码已复制。', 'success'); } else { state.credentialPassword = result.password; state.credentialVisible = true; text('vm-detail-root-password', result.password); byId('vm-detail-password-reveal').setAttribute('aria-pressed', 'true'); clearTimeout(state.credentialTimer); state.credentialTimer = setTimeout(clearCredential, 30000); } } catch (error) { toast(error.message, 'error'); } +} +async function loadKeys() { state.sshKeys = items(await api('/api/v1/ssh-keys')); renderKeys(); renderKeyCards('create'); renderKeyCards('reinstall'); } +function renderKeys() { + const container = byId('ssh-keys-list'); container.replaceChildren(); + if (!state.sshKeys.length) return container.append(makeElement('p', 'muted', '还没有公钥。')); + for (const key of state.sshKeys) { const row = makeElement('div', 'ssh-key-list-item'); row.append(makeElement('strong', '', key.name), makeElement('small', 'muted', key.fingerprint || '')); const button = actionButton('删除', async () => { if (!confirm(`删除公钥“${key.name}”?已创建的虚拟机不受影响。`)) return; try { await api(`/api/v1/ssh-keys/${encodeURIComponent(key.id)}`, { method: 'DELETE' }); await loadKeys(); } catch (error) { toast(error.message, 'error'); } }); row.append(button); container.append(row); } +} +function renderKeyCards(kind) { + const id = kind === 'create' ? 'vm-guest-ssh-key-cards' : 'reinstall-ssh-key-cards'; const container = byId(id); container.replaceChildren(); + if (!state.sshKeys.some(key => String(key.id) === state.selectedKeys[kind])) state.selectedKeys[kind] = ''; + for (const key of state.sshKeys) { const button = makeElement('button', 'ssh-key-option'); button.type = 'button'; button.setAttribute('aria-pressed', String(state.selectedKeys[kind] === String(key.id))); button.append(makeElement('strong', 'ssh-key-choice-label', key.name)); button.addEventListener('click', () => { state.selectedKeys[kind] = state.selectedKeys[kind] === String(key.id) ? '' : String(key.id); renderKeyCards(kind); }); container.append(button); } + if (!state.sshKeys.length) container.append(makeElement('p', 'muted', '暂无公钥,可先到“公钥管理”添加。不选公钥也会生成强密码。')); +} +function sourceMode() { return byId('create-form').querySelector('[name="source"]:checked').value; } +function updateSource() { const cloud = sourceMode() === 'cloud'; byId('vm-iso-field').hidden = cloud; byId('vm-iso').required = !cloud; byId('vm-iso').disabled = cloud; byId('vm-template-field').hidden = !cloud; byId('vm-template').disabled = !cloud; byId('vm-cloud-fields').hidden = !cloud; byId('vm-root-password').disabled = !cloud; byId('create-iso-tip').hidden = cloud; byId('create-cloud-tip').hidden = !cloud; } +function strongPassword(value) { return !value || (value.length >= 12 && new TextEncoder().encode(value).length <= 256 && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9\s]/.test(value) && !/[\r\n\0]/.test(value)); } +async function openCreate() { + state.selectedVmId = null; showView('create'); showError('create-error', ''); + try { const [plans] = await Promise.all([api('/api/v1/plans'), loadKeys()]); state.plans = items(plans); const select = byId('vm-plan'); const previous = select.value; select.replaceChildren(makeElement('option', '', state.plans.length ? '请选择套餐' : '暂无可售套餐')); select.firstElementChild.value = ''; for (const plan of state.plans) { const option = makeElement('option', '', `${plan.name} · ¥${plan.price}`); option.value = String(plan.id); select.append(option); } select.value = previous; if (!select.value && state.plans.length === 1) select.value = String(state.plans[0].id); await loadPlanResources(); updateSource(); } catch (error) { showError('create-error', error.message); } +} +async function loadPlanResources() { + const planId = byId('vm-plan').value; const plan = state.plans.find(item => String(item.id) === planId); const epoch = ++state.formEpoch; + state.resourceController?.abort(); state.resourceController = new AbortController(); state.resources = null; state.templates = []; renderTemplateCatalog('vm-template'); byId('vm-iso').replaceChildren(makeElement('option', '', '请选择套餐')); byId('vm-iso').firstElementChild.value = ''; + byId('create-submit').disabled = true; + if (!plan) { text('vm-plan-summary', '选择套餐后显示资源规格和一次性价格。'); return; } + text('vm-plan-summary', `${plan.cpu_cores} vCPU · ${plan.memory_mib} MiB · ${plan.disk_gib} GiB · ${plan.bandwidth_mbps} Mbps · ${plan.region || '地区未设置'} · 余额一次性支付 ¥${plan.price}`); + try { const resources = await api(`/api/v1/resources?plan_id=${encodeURIComponent(planId)}`, { signal: state.resourceController.signal }); if (epoch !== state.formEpoch) return; state.resources = resources; state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('vm-template'); const isos = items(resources.isos || resources.iso_images); const select = byId('vm-iso'); select.replaceChildren(makeElement('option', '', isos.length ? '选择安装镜像' : '没有可用 ISO')); select.firstElementChild.value = ''; for (const iso of isos) { const path = typeof iso === 'string' ? iso : iso.path || iso.name; if (!path) continue; const option = makeElement('option', '', typeof iso === 'string' ? iso.split('/').pop() : iso.name || iso.path.split('/').pop()); option.value = path; select.append(option); } byId('create-submit').disabled = false; } + catch (error) { if (epoch === state.formEpoch && error.name !== 'AbortError') showError('create-error', error.message); } +} +let orderIdempotency = ''; +async function buy(event) { + event.preventDefault(); if (state.mutationBusy) return; + const cloud = sourceMode() === 'cloud'; const password = byId('vm-root-password').value; + if (!strongPassword(password)) return showError('create-error', '密码需至少 12 个字符,包含大写、小写、数字和符号。'); + if (cloud && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。'); + if (!byId('vm-plan').value || !state.resources) return showError('create-error', '请先选择可用套餐。'); + if (!confirm('确认从账户余额一次性支付所选套餐价格并开通虚拟机?首版不包含自动续费。')) return; + state.mutationBusy = true; byId('create-submit').disabled = true; showError('create-error', ''); + if (!orderIdempotency) orderIdempotency = crypto.randomUUID(); + const body = { plan_id: Number(byId('vm-plan').value), name: byId('vm-name').value.trim(), source: sourceMode(), idempotency_key: orderIdempotency }; + if (cloud) { body.template_id = byId('vm-template').value; if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; if (password) body.root_password = password; } else body.iso_path = byId('vm-iso').value; + try { await api('/api/v1/orders', { method: 'POST', body }); orderIdempotency = ''; byId('vm-root-password').value = ''; toast('订单已提交,后台持续开通中。', 'success'); showView('orders'); await loadOrders(); } + catch (error) { showError('create-error', error.message); } + finally { delete body.root_password; state.mutationBusy = false; byId('create-submit').disabled = !state.resources; } +} +function formatOrderDate(value) { const date = new Date(typeof value === 'number' ? value * 1000 : value); return Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; } +async function loadOrders() { + try { + const orders = items(await api('/api/v1/orders')); + const container = byId('orders-list'); + container.replaceChildren(); + if (!orders.length) return container.append(makeElement('p', 'muted', '暂无订单。')); + const labels = { queued: '等待开通', pending: '等待开通', provisioning: '开通中', running: '开通中', completed: '已开通', succeeded: '已开通', active: '已开通', failed: '失败', refunded: '已退款', needs_attention: '需要管理员核查', uncertain: '需要管理员核查' }; + for (const order of orders) { + const row = makeElement('div', 'cloud-order'); + const detail = makeElement('div', ''); + detail.append(makeElement('strong', '', order.name || order.plan_name || `订单 #${order.id} · 套餐 #${order.plan_id ?? '—'}`), makeElement('p', 'muted', `¥${order.price ?? order.amount ?? '—'} · ${formatOrderDate(order.created_at)}`)); + if (order.error || order.message || order.phase) detail.append(makeElement('p', '', order.error || order.message || order.phase)); + row.append(detail, makeElement('span', `state-pill ${['completed', 'succeeded', 'active'].includes(order.status) ? 'running' : 'other'}`, labels[order.status] || order.status)); + if (order.job_id) row.append(actionButton('查看任务进度', async () => { + try { const job = await api(`/api/v1/jobs/${encodeURIComponent(order.job_id)}`); detail.append(makeElement('p', job.error ? 'form-error' : 'muted', job.error || job.phase || `任务状态:${job.status}`)); } + catch (error) { toast(error.message, 'error'); } + })); + if (order.vm_id || order.instance_id || order.vm_uuid) row.append(actionButton('查看虚拟机', async () => { + await loadVms(); + const vm = state.vms.find(item => item.api_id === String(order.vm_id || order.instance_id) || item.uuid === order.vm_uuid); + if (vm) openVmDetail(vm.uuid); else toast('虚拟机尚未出现在列表,请稍后刷新。'); + })); + container.append(row); + } + } catch (error) { showError('cloud-page-error', error.message); } +} +async function openReinstall(vm) { + showView('reinstall'); text('reinstall-subtitle', `${vm.name} · 保留原有公网网络参数,重新创建系统盘。`); text('reinstall-public-ip', vmIp(vm)); byId('reinstall-confirm-name').value = ''; byId('reinstall-root-password').value = ''; byId('reinstall-template').value = ''; showError('reinstall-error', ''); byId('reinstall-progress').hidden = true; byId('reinstall-result').hidden = true; byId('reinstall-fields').hidden = false; + try { const resources = await api(`/api/v1/resources?vm_id=${encodeURIComponent(vm.api_id)}`); state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('reinstall-template'); await loadKeys(); } catch (error) { showError('reinstall-error', error.message); } +} +async function pollJob(kind, id, phaseId, errorId) { + const path = `/api/v1/jobs/${encodeURIComponent(id)}`; + for (let attempt = 0; attempt < 600; attempt++) { if (document.visibilityState === 'hidden') await new Promise(resolve => setTimeout(resolve, 1000)); const job = await api(path); if (phaseId) text(phaseId, job.phase || job.status || '正在处理…'); if (['completed', 'succeeded', 'done'].includes(job.status)) return job; if (['failed', 'cancelled', 'needs_attention', 'uncertain'].includes(job.status)) throw new Error(job.error || job.message || '任务失败,请核查虚拟机状态。'); await new Promise(resolve => setTimeout(resolve, 2000)); } + throw new Error('任务仍在处理,可稍后刷新详情。不要重复提交。'); +} +async function reinstall(event) { + event.preventDefault(); const vm = selectedVm(); if (!vm || state.mutationBusy) return; + if (byId('reinstall-confirm-name').value !== vm.name) return showError('reinstall-error', '请输入完整虚拟机名称确认。'); + const password = byId('reinstall-root-password').value; if (!strongPassword(password)) return showError('reinstall-error', '密码需至少 12 个字符,包含大写、小写、数字和符号。'); + const template = byId('reinstall-template').value; if (!template) return showError('reinstall-error', '请选择系统镜像版本。'); + state.mutationBusy = true; byId('reinstall-submit').disabled = true; + const body = { template_id: template, confirmation_name: vm.name }; if (state.selectedKeys.reinstall) body.ssh_key_id = state.selectedKeys.reinstall; if (password) body.root_password = password; + try { const result = await api(`${vmPath(vm)}/reinstall`, { method: 'POST', body }); byId('reinstall-root-password').value = ''; byId('reinstall-progress').hidden = false; if (result.job_id) await pollJob('reinstall', result.job_id, 'reinstall-phase', 'reinstall-error'); toast('重装任务已完成,请等待系统初始化。', 'success'); await loadVms(); if (selectedVm()) openVmDetail(vm.uuid); } + catch (error) { showError('reinstall-error', error.message); } + finally { delete body.root_password; state.mutationBusy = false; byId('reinstall-submit').disabled = false; byId('reinstall-progress').hidden = true; } +} +async function openRescue(vm) { showView('rescue'); text('rescue-subtitle', `${vm.name} · 挂载救援 ISO 并启动救援环境。`); byId('rescue-confirm-name').value = ''; byId('rescue-template-id').value = ''; showError('rescue-error', ''); try { const [resources, status] = await Promise.all([api(`/api/v1/resources?vm_id=${encodeURIComponent(vm.api_id)}`), api(`${vmPath(vm)}/rescue`)]); const container = byId('rescue-template-cards'); container.replaceChildren(); for (const template of items(resources.rescue_templates)) { const button = makeElement('button', 'ssh-key-option', template.name); button.type = 'button'; button.dataset.templateId = String(template.id); button.setAttribute('aria-pressed', 'false'); button.addEventListener('click', () => { byId('rescue-template-id').value = template.id; container.querySelectorAll('button').forEach(item => item.setAttribute('aria-pressed', String(item === button))); }); container.append(button); } if (!container.children.length) container.append(makeElement('p', 'muted', '暂无救援模板,请联系管理员。')); renderRescueStatus(status); } catch (error) { showError('rescue-error', error.message); } } +function renderRescueStatus(status) { state.rescueActive = status.active === true || status.rescue_mode === true; state.rescueStaged = status.staged === true || status.rescue_staged === true; text('rescue-status', status.message || (state.rescueActive ? '当前已进入救援模式。' : state.rescueStaged ? '救援镜像已预挂载,正常关机失败时可以强制冷启动进入救援。' : '尚未挂载救援镜像。')); byId('rescue-force-start').hidden = !state.rescueStaged; byId('rescue-exit').hidden = !state.rescueActive && !state.rescueStaged; } +async function rescueAction(action) { + const vm = selectedVm(); if (!vm || state.mutationBusy) return; if (byId('rescue-confirm-name').value !== vm.name) return showError('rescue-error', '请输入完整虚拟机名称确认。'); + if (action === 'load' && !byId('rescue-template-id').value) return showError('rescue-error', '请选择救援模板。'); + if (action === 'force-start' && !confirm('正常关机未成功。强制断电并冷启动进入已挂载的救援环境可能丢失数据,确认继续?')) return; + state.mutationBusy = true; showError('rescue-error', ''); + try { const body = { confirmation_name: vm.name }; if (action === 'load') body.template_id = byId('rescue-template-id').value; if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body }); if (result.job_id) await pollJob('rescue', result.job_id, 'rescue-status', 'rescue-error'); toast('救援操作完成。', 'success'); } + catch (error) { showError('rescue-error', error.message); } + finally { state.mutationBusy = false; try { renderRescueStatus(await api(`${vmPath(vm)}/rescue`)); } catch (error) { showError('rescue-error', error.message); } await loadVms(); } +} +function closeConsole() { state.consoleToken++; state.rfb?.disconnect(); state.rfb = null; byId('console-modal').hidden = true; byId('console-password-form').hidden = true; byId('console-password').value = ''; byId('console-cad').disabled = true; } +async function openConsole(vm) { + closeConsole(); const token = ++state.consoleToken; byId('console-modal').hidden = false; text('console-title', `${vm.name} · 控制台`); text('console-status', '正在申请短期控制台连接…'); const placeholder = byId('console-placeholder'); placeholder.hidden = false; + try { const [ticket, module] = await Promise.all([api(`${vmPath(vm)}/console-ticket`, { method: 'POST' }), import('/cloud/vendor/novnc/core/rfb.js')]); if (token !== state.consoleToken) return; const url = new URL(ticket.websocket_path, location.href); if (url.origin !== location.origin || url.pathname !== '/engine-console' || url.search || url.hash || typeof ticket.ticket !== 'string' || !/^[A-Za-z0-9_-]+$/.test(ticket.ticket)) throw new Error('控制台地址或票据无效。'); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const rfb = new module.default(byId('console-stage'), url.href, { shared: true, wsProtocols: ['cloud-ticket.' + ticket.ticket] }); state.rfb = rfb; rfb.scaleViewport = true; rfb.resizeSession = false; placeholder.hidden = true; rfb.addEventListener('connect', () => { if (state.rfb !== rfb) return; text('console-status', '已连接'); byId('console-cad').disabled = false; }); rfb.addEventListener('disconnect', event => { if (state.rfb !== rfb) return; text('console-status', event.detail?.clean ? '连接已关闭' : '连接已中断,请关闭后重试。'); byId('console-cad').disabled = true; }); rfb.addEventListener('credentialsrequired', () => { if (state.rfb !== rfb) return; byId('console-password-form').hidden = false; byId('console-password').focus(); text('console-status', '请输入 VNC 密码'); }); } catch (error) { if (token === state.consoleToken) { text('console-status', `连接失败:${error.message}`); placeholder.hidden = false; } } +} +function stateCategory(value) { + const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); + if (normalized === "running" || normalized === "blocked") return "running"; + if (["shutoff", "stopped", "crashed"].includes(normalized)) return "stopped"; + return "other"; +} + +function stateLabel(value) { + const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); + const labels = { + running: "运行中", blocked: "运行中", shutoff: "已关机", stopped: "已关机", + shutdown: "关机中", crashed: "已崩溃", paused: "已暂停", pmsuspended: "已挂起", + nostate: "未知", unknown: "未知", + }; + return labels[normalized] || String(value || "未知"); +} + +function diskLabel(vm) { + if (Array.isArray(vm.disks) && vm.disks.length) { + const size = vm.disks.reduce((sum, disk) => { + const capacity = Number(disk.capacity_gib ?? disk.size_gib ?? 0); + return sum + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0); + }, 0); + if (size > 0) return `${Math.round(size * 100) / 100} GiB`; + } + if (Number.isFinite(Number(vm.disk_gib)) && Number(vm.disk_gib) > 0) return `${vm.disk_gib} GiB`; + return "—"; +} + +function vmSystemInfo(vm) { + if (vm.os_source === "iso") return { label: "安装镜像", value: String(vm.install_iso || "未识别") }; + if (vm.os_source === "cloud_template") return { label: "系统镜像", value: String(vm.os_name || "未识别") }; + return { label: "系统", value: String(vm.os_name || "未识别") }; +} + +function vmRegion(vm) { + return String(vm.region || "").trim() || "未设置"; +} + +function vmIp(vm) { + return String(vm.public_ip_cidr || "").trim().split("/")[0] || "未获取"; +} + +function vmCreatedAt(vm) { + const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; + if (!value) return "未记录"; + const date = new Date(value); + if (!Number.isFinite(date.getTime())) return "未记录"; + const pad = (number) => String(number).padStart(2, "0"); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`; +} + +function vmCreatedAgo(vm, now = Date.now()) { + const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; + if (!value) return "未记录"; + const created = Date.parse(value); + if (!Number.isFinite(created)) return "未记录"; + const elapsed = Math.max(0, now - created); + const minute = 60 * 1000; + const hour = 60 * minute; + const day = 24 * hour; + const month = 30 * day; + if (elapsed < minute) return "创建于刚刚"; + if (elapsed < hour) return `创建于 ${Math.floor(elapsed / minute)} 分钟前`; + if (elapsed < day) return `创建于 ${Math.floor(elapsed / hour)} 小时前`; + if (elapsed < month) return `创建于 ${Math.floor(elapsed / day)} 天前`; + return `创建于 ${Math.floor(elapsed / month)} 个月前`; +} + +function makeCell(row, className = "") { + const cell = document.createElement("td"); + if (className) cell.className = className; + row.append(cell); + return cell; +} + +function makeElement(tag, className, content) { + const element = document.createElement(tag); + if (className) element.className = className; + if (content !== undefined) element.textContent = String(content); + return element; +} + +function makeCopyIconButton(value, label) { + const button = makeElement("button", "vm-copy-icon"); + button.type = "button"; + button.title = `复制${label}`; + button.setAttribute("aria-label", `复制${label}`); + const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + icon.setAttribute("viewBox", "0 0 24 24"); + icon.setAttribute("aria-hidden", "true"); + const back = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + for (const [name, attribute] of Object.entries({ x: "8", y: "8", width: "12", height: "12", rx: "2" })) { + back.setAttribute(name, attribute); + } + const front = document.createElementNS("http://www.w3.org/2000/svg", "path"); + front.setAttribute("d", "M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"); + icon.append(back, front); + button.append(icon); + button.addEventListener("click", async () => { + try { + await copyText(value); + toast(`${label}已复制。`, "success"); + } catch (error) { + toast(error.message, "error"); + } + }); + return button; +} + +function actionButton(label, handler, options = {}) { + const button = makeElement("button", `row-button ${options.variant || ""}`, label); + button.type = "button"; + button.disabled = Boolean(options.disabled); + if (options.key) button.dataset.vmAction = options.key; + if (options.title) button.title = options.title; + button.addEventListener("click", handler); + return button; +} + +function renderVMs(connectionError = false) { + const all = state.vms; + const runningCount = all.filter((vm) => stateCategory(vm.state) === "running").length; + const stoppedCount = all.filter((vm) => stateCategory(vm.state) === "stopped").length; + text("stat-total", String(all.length)); + text("stat-running", String(runningCount)); + text("stat-stopped", String(stoppedCount)); + + const query = byId("search-input").value.trim().toLocaleLowerCase(); + const filter = byId("state-filter").value; + const filtered = all.filter((vm) => { + const matchesText = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.region, vm.os_name, vm.install_iso] + .some((value) => String(value || "").toLocaleLowerCase().includes(query)); + return matchesText && (filter === "all" || stateCategory(vm.state) === filter); + }); + text("inventory-count", `${filtered.length} 台虚拟机${filtered.length !== all.length ? ` · 共 ${all.length} 台` : ""}`); + const tbody = byId("vm-table-body"); + const focusedVmId = document.activeElement?.classList.contains("vm-name-link") + ? document.activeElement.dataset.vmUuid : null; + tbody.replaceChildren(); + const empty = byId("empty-state"); + empty.hidden = filtered.length !== 0; + if (!filtered.length) { + if (connectionError) { + text("empty-title", "无法加载虚拟机"); + text("empty-description", "请检查面板与宿主机的连接,然后点击刷新。"); + } else if (all.length) { + text("empty-title", "没有匹配的虚拟机"); + text("empty-description", "尝试更换搜索词或状态筛选。"); + } else { + text("empty-title", "还没有虚拟机"); + text("empty-description", "点击右上角“购买并开通”开始。"); + } + return; + } + + for (const vm of filtered) { + const uuid = String(vm.uuid || ""); + const category = stateCategory(vm.state); + const row = document.createElement("tr"); + const identity = makeElement("div", "vm-identity"); + identity.append(makeElement("div", "vm-icon", "▣")); + const identityText = makeElement("div"); + const nameButton = makeElement("button", "vm-name-link", vm.name || "未命名虚拟机"); + nameButton.type = "button"; + nameButton.disabled = !uuid; + nameButton.dataset.vmUuid = uuid; + nameButton.setAttribute("aria-label", `管理虚拟机 ${vm.name || uuid}`); + nameButton.addEventListener("click", () => openVmDetail(uuid)); + identityText.append(nameButton); + const uuidRow = makeElement("span", "vm-uuid-row"); + const uuidText = makeElement("span", "vm-id", uuid || "UUID 未知"); + if (uuid) uuidText.title = uuid; + uuidRow.append(uuidText); + if (uuid) uuidRow.append(makeCopyIconButton(uuid, "UUID")); + identityText.append(uuidRow); + identity.append(identityText); + const identityCell = makeCell(row); + identityCell.dataset.label = "虚拟机"; + identityCell.append(identity); + + const stateCell = makeCell(row); + stateCell.dataset.label = "状态"; + stateCell.append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state))); + const regionCell = makeCell(row); + regionCell.dataset.label = "地区"; + regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm))); + const system = vmSystemInfo(vm); + const systemCell = makeCell(row); + systemCell.dataset.label = system.label; + systemCell.append(makeElement("span", "vm-metadata", system.value)); + const ipCell = makeCell(row); + ipCell.dataset.label = "已配置公网 IP"; + const ip = vmIp(vm); + const ipRow = makeElement("span", "vm-ip-copy-row"); + ipRow.append(makeElement("span", "vm-metadata vm-ip", ip)); + if (ip !== "未获取") ipRow.append(makeCopyIconButton(ip, "公网 IP")); + ipCell.append(ipRow); + const spec = makeElement("div", "vm-spec"); + spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`)); + spec.append(makeElement("small", "", "计算资源")); + const specCell = makeCell(row); + specCell.dataset.label = "规格"; + specCell.append(spec); + const diskCell = makeCell(row); + diskCell.dataset.label = "磁盘"; + diskCell.append(makeElement("span", "vm-spec", diskLabel(vm))); + tbody.append(row); + } + if (focusedVmId) { + const replacement = Array.from(tbody.querySelectorAll(".vm-name-link")) + .find((button) => button.dataset.vmUuid === focusedVmId); + replacement?.focus({ preventScroll: true }); + } +} + +const VM_METRICS_RANGE_SECONDS = { "1h": 3600, "24h": 86400, "7d": 604800, "30d": 2592000 }; +const VM_METRIC_CHARTS = [ + { id: "cpu", title: "CPU 使用率", unit: "percent", series: [{ key: "cpu_percent", color: "#0f9eaa" }] }, + { id: "memory", title: "内存用量", unit: "memory", series: [{ key: "memory_used_mib", color: "#4781cf" }, { key: "memory_total_mib", color: "#a4b7d7", dash: "6 5" }] }, + { id: "disk", title: "磁盘 I/O", unit: "rate", series: [{ key: "disk_read_bps", color: "#477dc9" }, { key: "disk_write_bps", color: "#e59c46" }] }, + { id: "network", title: "网络速率", unit: "rate", series: [{ key: "network_rx_bps", color: "#17a685" }, { key: "network_tx_bps", color: "#926ed0" }] }, +]; + +function metricViewVisible() { + return Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden + && !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden; +} + +function stopVmMetrics() { + if (state.metricsPollTimer) window.clearInterval(state.metricsPollTimer); + state.metricsPollTimer = null; + if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer); + state.metricsResizeTimer = null; + state.metricsRequest?.controller.abort(); + state.metricsRequest = null; +} + +function startVmMetrics() { + if (!metricViewVisible()) return; + void loadVmMetrics(); + if (!state.metricsPollTimer) { + state.metricsPollTimer = window.setInterval(() => { + if (metricViewVisible()) void loadVmMetrics(); + }, 60000); + } +} + +function setVmMetricsStatus(message, warning = false) { + const status = byId("vm-metrics-status"); + status.textContent = message; + status.classList.toggle("warning", warning); +} + +function clearVmMetrics(message) { + state.metricsPayload = null; + setVmMetricsStatus(message); + for (const chart of VM_METRIC_CHARTS) { + text(`vm-metric-${chart.id}-summary`, "—"); + byId(`vm-metric-${chart.id}-plot`).replaceChildren(makeElement("p", "vm-metric-empty", message)); + } +} + +async function loadVmMetrics() { + if (!metricViewVisible()) return; + const vmId = state.selectedVmId; + const range = state.metricsRange; + const previous = state.metricsRequest; + if (previous?.vmId === vmId && previous.range === range) return; + previous?.controller.abort(); + const request = { vmId, range, controller: new AbortController() }; + state.metricsRequest = request; + setVmMetricsStatus("正在更新监控数据…"); + try { + const payload = await api(`${vmPath()}/metrics?range=${encodeURIComponent(range)}`, { + signal: request.controller.signal, + }); + if (request !== state.metricsRequest || !metricViewVisible()) return; + if (!Array.isArray(payload?.points)) { + throw new Error("监控数据格式无效。"); + } + renderVmMetrics(payload); + } catch (error) { + if (request !== state.metricsRequest || request.controller.signal.aborted || !metricViewVisible()) return; + setVmMetricsStatus(`监控数据暂时无法加载:${error.message}。已显示的数据可能不是最新。`, true); + } finally { + if (request === state.metricsRequest) state.metricsRequest = null; + } +} + +function metricNumber(value) { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; +} + +function formatMetricRate(value) { + if (value === null) return "无统计"; + const units = ["B/s", "KB/s", "MB/s", "GB/s", "TB/s"]; + let amount = value; + let index = 0; + while (amount >= 1000 && index < units.length - 1) { amount /= 1000; index += 1; } + return `${amount.toFixed(index === 0 ? (amount < 1 && amount > 0 ? 2 : 0) : amount < 10 ? 2 : 1)} ${units[index]}`; +} + +function formatMetricMemory(value) { + if (value === null) return "无统计"; + return value >= 1024 ? `${(value / 1024).toFixed(value < 10240 ? 2 : 1)} GiB` : `${Math.round(value)} MiB`; +} + +function formatMetricValue(value, unit) { + if (value === null) return "无统计"; + if (unit === "percent") return `${value.toFixed(1)}%`; + if (unit === "memory") return formatMetricMemory(value); + return formatMetricRate(value); +} + +function formatMetricTime(timestamp) { + return new Date(timestamp * 1000).toLocaleString("zh-CN", { + month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", + }); +} + +function metricSummary(chart, points) { + const latest = [...points].reverse().find((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); + if (!latest) return "暂无统计"; + const value = (key) => metricNumber(latest[key]); + if (chart.id === "cpu") return formatMetricValue(value("cpu_percent"), "percent"); + if (chart.id === "memory") return `已使用(估算)${formatMetricMemory(value("memory_used_mib"))} · 总量 ${formatMetricMemory(value("memory_total_mib"))}`; + if (chart.id === "disk") return `读取 ${formatMetricRate(value("disk_read_bps"))} · 写入 ${formatMetricRate(value("disk_write_bps"))}`; + return `接收 ${formatMetricRate(value("network_rx_bps"))} · 发送 ${formatMetricRate(value("network_tx_bps"))}`; +} + +function metricChartEmptyText(chart) { + if (chart.id === "memory") return "暂无内存统计;虚拟机可能未提供气球驱动数据。"; + if (chart.id === "disk" || chart.id === "network") return "暂无速率数据;首次采样或停机时无法计算速率。"; + return "当前时间范围内暂无 CPU 采样数据。"; +} + +function metricNiceMax(value) { + if (value <= 0) return 1; + const base = 10 ** Math.floor(Math.log10(value)); + for (const step of [1, 1.5, 2, 2.5, 5, 10]) { + if (value <= step * base) return step * base; + } + return 10 * base; +} + +function metricSvgElement(tag, attributes = {}) { + const element = document.createElementNS("http://www.w3.org/2000/svg", tag); + for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value)); + return element; +} + +function drawMetricChart(chart, points, start, end, intervalSeconds) { + const plot = byId(`vm-metric-${chart.id}-plot`); + const summary = metricSummary(chart, points); + text(`vm-metric-${chart.id}-summary`, summary); + const hasData = points.some((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); + if (!hasData) { + plot.replaceChildren(makeElement("p", "vm-metric-empty", metricChartEmptyText(chart))); + return; + } + + const values = points.flatMap((point) => chart.series.map((series) => metricNumber(point[series.key]))).filter((value) => value !== null); + const maximum = chart.unit === "percent" ? Math.max(100, metricNiceMax(Math.max(...values))) : metricNiceMax(Math.max(...values)); + // A fixed 640px viewBox shrinks axis text to ~4px inside a phone card. + const width = Math.max(240, Math.floor(plot.clientWidth || 640)); + const height = Math.max(180, Math.floor(plot.clientHeight || 216)); + const left = 64; + const right = 18; + const top = 14; + const bottom = 37; + const plotWidth = width - left - right; + const plotHeight = height - top - bottom; + const x = (timestamp) => left + Math.max(0, Math.min(1, (timestamp - start) / (end - start))) * plotWidth; + const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight; + const svg = metricSvgElement("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": `${chart.title},${byId("vm-metrics-range").selectedOptions[0]?.textContent || "当前范围"};最近记录:${summary}` }); + for (const fraction of [1, 0.5, 0]) { + const lineY = top + (1 - fraction) * plotHeight; + svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" })); + const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" }); + label.textContent = formatMetricValue(fraction * maximum, chart.unit); + svg.append(label); + } + for (const [fraction, anchor] of [[0, "start"], [0.5, "middle"], [1, "end"]]) { + const label = metricSvgElement("text", { x: left + fraction * plotWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" }); + label.textContent = formatMetricTime(start + fraction * (end - start)); + svg.append(label); + } + + const maxGap = intervalSeconds * 2.5; + for (const series of chart.series) { + const segments = []; + let segment = []; + for (const point of points) { + const value = metricNumber(point[series.key]); + if (value === null) { + if (segment.length) segments.push(segment); + segment = []; + continue; + } + if (segment.length && point.timestamp - segment[segment.length - 1].timestamp > maxGap) { + segments.push(segment); + segment = []; + } + segment.push({ timestamp: point.timestamp, value }); + } + if (segment.length) segments.push(segment); + for (const group of segments) { + if (group.length > 1) { + const path = metricSvgElement("path", { + d: group.map((point, index) => `${index ? "L" : "M"}${x(point.timestamp).toFixed(2)} ${y(point.value).toFixed(2)}`).join(" "), + fill: "none", stroke: series.color, "stroke-width": 2.6, + "stroke-linecap": "round", "stroke-linejoin": "round", + ...(series.dash ? { "stroke-dasharray": series.dash } : {}), + }); + svg.append(path); + } + const last = group[group.length - 1]; + svg.append(metricSvgElement("circle", { cx: x(last.timestamp), cy: y(last.value), r: group.length === 1 ? 3.8 : 2.8, fill: series.color })); + } + } + plot.replaceChildren(svg); +} + +function renderVmMetrics(payload) { + state.metricsPayload = payload; + const intervalSeconds = Math.max(1, Number(payload.interval_seconds) || 60); + const rangeSeconds = VM_METRICS_RANGE_SECONDS[state.metricsRange]; + const now = Math.floor(Date.now() / 1000); + const points = payload.points + .filter((point) => Number.isFinite(Number(point?.timestamp)) && Number(point.timestamp) >= now - rangeSeconds - intervalSeconds && Number(point.timestamp) <= now + intervalSeconds) + .map((point) => ({ ...point, timestamp: Number(point.timestamp) })) + .sort((a, b) => a.timestamp - b.timestamp); + const end = Math.max(now, points.length ? points[points.length - 1].timestamp : now); + const start = end - rangeSeconds; + const visiblePoints = points.filter((point) => point.timestamp >= start && point.timestamp <= end); + for (const chart of VM_METRIC_CHARTS) drawMetricChart(chart, visiblePoints, start, end, intervalSeconds); + if (!visiblePoints.length) { + setVmMetricsStatus("当前时间范围内没有采样记录。虚拟机运行后,通常需等待下一次后台采样。", true); + return; + } + const latest = visiblePoints[visiblePoints.length - 1].timestamp; + // Bucket width grows for long ranges; freshness still follows the 60s + // collector cadence, not the downsampling bucket width. + const stale = end - latest > 60 * 2.5; + setVmMetricsStatus(`${visiblePoints.length} 个采样点 · ${stale ? "最近历史记录" : "最近采样"} ${formatMetricTime(latest)} · 每分钟自动刷新${stale ? "(当前无新数据)" : ""}`, stale); +} + +const TEMPLATE_FAMILY_NAMES = { + almalinux: "AlmaLinux", + debian: "Debian", + centos: "CentOS", + centosstream: "CentOS", + ubuntu: "Ubuntu", +}; + +const TEMPLATE_ICON_PATHS = { + AlmaLinux: "/cloud/almalinux-icon.svg", + Debian: "/cloud/debian-icon.svg", + CentOS: "/cloud/centos-icon.svg", + Ubuntu: "/cloud/ubuntu-icon.svg", +}; + +function templateSystem(item) { + const id = String(item?.id || ""); + const familyKey = String(item?.os_family || "").trim().toLowerCase().replace(/[\s_-]+/g, ""); + const namedFamily = Object.prototype.hasOwnProperty.call(TEMPLATE_FAMILY_NAMES, familyKey) + ? TEMPLATE_FAMILY_NAMES[familyKey] : ""; + const family = namedFamily + || (/^alma(?:9|10)-/.test(id) ? "AlmaLinux" : "其他系统"); + const oldVersion = /^alma(9|10)-/.exec(id)?.[1] || ""; + const version = /^[0-9]+$/.test(String(item?.os_version || "")) + ? String(item.os_version) : oldVersion; + return { family, version }; +} + +function templateIcon(family, className) { + const logoPath = TEMPLATE_ICON_PATHS[family]; + const icon = makeElement("span", `${className}${logoPath ? " system" : ""}`); + icon.setAttribute("aria-hidden", "true"); + if (logoPath) { + const logo = makeElement("img", "template-system-logo"); + logo.src = logoPath; + logo.alt = ""; + icon.append(logo); + } else { + icon.textContent = "◈"; + } + return icon; +} + +function renderTemplateCatalog(inputId) { + const input = byId(inputId); + const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog"); + const opened = new Set(Array.from(container.querySelectorAll("details[open]"), (detail) => detail.dataset.family)); + const groups = new Map(); + for (const item of state.templates) { + if (!item?.id) continue; + const { family, version } = templateSystem(item); + if (!groups.has(family)) groups.set(family, []); + groups.get(family).push({ item, version }); + } + if (!groups.size) { + input.value = ""; + container.replaceChildren(makeElement("p", "template-catalog-empty", state.admin + ? "暂无云镜像,请先到“云镜像模板”页面导入。" + : "暂无可用云镜像,请联系管理员导入模板。")); + return; + } + if (!state.templates.some((item) => String(item.id) === input.value)) input.value = ""; + const cards = []; + for (const [family, entries] of groups) { + entries.sort((a, b) => Number(b.version || 0) - Number(a.version || 0) + || String(a.item.name || "").localeCompare(String(b.item.name || ""), "zh-CN")); + const card = makeElement("details", "template-family-card"); + card.dataset.family = family; + card.open = opened.has(family) || entries.some(({ item }) => String(item.id) === input.value); + const summary = makeElement("summary", "template-family-summary"); + const icon = templateIcon(family, "template-family-icon"); + summary.append(icon, makeElement("strong", "", family), makeElement("span", "template-family-arrow", "⌄")); + const versions = makeElement("div", "template-versions"); + versions.setAttribute("role", "group"); + versions.setAttribute("aria-label", `${family} 可用版本`); + for (const { item } of entries) { + const id = String(item.id); + const name = String(item.name || id); + const option = makeElement("button", "template-version-option"); + option.type = "button"; + option.dataset.templateId = id; + option.setAttribute("aria-pressed", String(input.value === id)); + option.setAttribute("aria-label", `选择模板 ${name}`); + option.append(makeElement("strong", "", name)); + option.addEventListener("click", () => { + input.value = id; + container.querySelectorAll(".template-version-option").forEach((button) => { + button.setAttribute("aria-pressed", String(button.dataset.templateId === id)); + }); + if (inputId === "vm-template") showError("create-error", ""); + else showError("reinstall-error", ""); + }); + versions.append(option); + } + card.append(summary, versions); + cards.push(card); + } + container.replaceChildren(...cards); +} +document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async () => { const view = button.dataset.view; try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'orders') await loadOrders(); } } catch (error) { showError('cloud-page-error', error.message); } })); +for (const id of ['refresh-button', 'vm-detail-refresh-button']) byId(id).addEventListener('click', loadVms); +byId('create-button').addEventListener('click', openCreate); byId('create-back').addEventListener('click', () => showView('list')); byId('vm-detail-back-button').addEventListener('click', () => { state.selectedVmId = null; showView('list'); }); byId('ssh-keys-back-button').addEventListener('click', () => showView('list')); +for (const id of ['reinstall-back', 'reinstall-cancel', 'rescue-back']) byId(id).addEventListener('click', () => { if (!state.mutationBusy) { const vm = selectedVm(); if (vm) openVmDetail(vm.uuid); else showView('list'); } }); +byId('search-input').addEventListener('input', () => renderVMs()); byId('state-filter').addEventListener('change', () => renderVMs()); byId('vm-plan').addEventListener('change', () => { orderIdempotency = ''; void loadPlanResources(); }); byId('create-form').querySelectorAll('[name="source"]').forEach(radio => radio.addEventListener('change', updateSource)); +byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('orders-refresh').addEventListener('click', loadOrders); +for (const id of ['vm-open-ssh-keys', 'reinstall-open-ssh-keys']) byId(id).addEventListener('click', async () => { showView('keys'); try { await loadKeys(); } catch (error) { toast(error.message, 'error'); } }); +byId('ssh-key-form').addEventListener('submit', async event => { event.preventDefault(); const button = byId('ssh-key-save-button'); button.disabled = true; showError('ssh-key-form-error', ''); try { await api('/api/v1/ssh-keys', { method: 'POST', body: { name: byId('ssh-key-name').value.trim(), public_key: byId('ssh-key-public-key').value.trim() } }); byId('ssh-key-form').reset(); await loadKeys(); toast('公钥已保存。', 'success'); } catch (error) { showError('ssh-key-form-error', error.message); } finally { button.disabled = false; } }); +byId('ssh-key-file').addEventListener('change', async event => { const file = event.target.files?.[0]; if (!file) return; if (file.size > 16384) return showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。'); const content = await file.text(); if (/PRIVATE KEY/.test(content)) return showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。'); byId('ssh-key-public-key').value = content.trim(); }); +byId('vm-detail-ip-copy').addEventListener('click', async () => { try { await copyText(vmIp(selectedVm())); toast('公网 IP 已复制。'); } catch (error) { toast(error.message, 'error'); } }); byId('vm-detail-password-reveal').addEventListener('click', () => credential()); byId('vm-detail-password-copy').addEventListener('click', () => credential(true)); +byId('vm-metrics-range').addEventListener('change', () => { state.metricsRange = byId('vm-metrics-range').value; state.metricsRequest?.controller.abort(); state.metricsRequest = null; void loadVmMetrics(); }); window.addEventListener('resize', () => { clearTimeout(state.metricsResizeTimer); state.metricsResizeTimer = setTimeout(() => { if (state.metricsPayload && state.view === 'detail') renderVmMetrics(state.metricsPayload); }, 150); }); +byId('console-modal').querySelector('[data-close-modal]').addEventListener('click', closeConsole); byId('console-cad').addEventListener('click', () => state.rfb?.sendCtrlAltDel()); byId('console-fullscreen').addEventListener('click', () => { byId('console-stage').requestFullscreen?.().catch(error => toast(error.message, 'error')); }); byId('console-password-form').addEventListener('submit', event => { event.preventDefault(); state.rfb?.sendCredentials({ password: byId('console-password').value }); byId('console-password').value = ''; byId('console-password-form').hidden = true; }); window.addEventListener('keydown', event => { if (event.key === 'Escape') closeConsole(); }); +document.addEventListener('visibilitychange', () => { if (document.hidden) clearCredential(); else { void loadVms(); if (state.view === 'detail') startVmMetrics(); } }); window.addEventListener('pagehide', () => { clearCredential(); closeConsole(); state.resourceController?.abort(); }); byId('logout-button').addEventListener('click', () => { clearCredential(); closeConsole(); location.assign('/auth/logout'); }); +async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; text('current-username', state.username); byId('cloud-admin-link').hidden = !state.admin; showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (state.view === 'orders') void loadOrders(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } } +window.addEventListener('hashchange', () => { if (state.csrfToken) void routeHash(); }); +void initialize(); diff --git a/web/public/cloud/centos-icon.svg b/web/public/cloud/centos-icon.svg new file mode 100644 index 00000000..ba433b4e --- /dev/null +++ b/web/public/cloud/centos-icon.svg @@ -0,0 +1 @@ + diff --git a/web/public/cloud/client.css b/web/public/cloud/client.css new file mode 100644 index 00000000..72aa2846 --- /dev/null +++ b/web/public/cloud/client.css @@ -0,0 +1,2 @@ +/* Client-only additions. The admin layout never loads this stylesheet. */ +.cloud-orders { padding: 24px; } .cloud-order { border-bottom: 1px solid var(--border, #e5edf2); padding: 18px 0; display: flex; justify-content: space-between; gap: 16px; flex-wrap: wrap; } .cloud-order p { margin: 8px 0 0; } .cloud-order:last-child { border: 0; } .cloud-order code { overflow-wrap: anywhere; } .cloud-plan-summary { display: flex; flex-wrap: wrap; gap: 12px; } .cloud-page-progress { margin: 16px 0; } .sidebar a.sidebar-link { text-decoration: none; } .vm-detail-secret { max-width: 100%; overflow-wrap: anywhere; } .ssh-key-choice-label { align-self: center; } #vm-plan-summary { display: block; padding: 16px; } #cloud-page-error { margin-bottom: 20px; } diff --git a/web/public/cloud/debian-icon.svg b/web/public/cloud/debian-icon.svg new file mode 100644 index 00000000..7fa03875 --- /dev/null +++ b/web/public/cloud/debian-icon.svg @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css new file mode 100644 index 00000000..37cda1e9 --- /dev/null +++ b/web/public/cloud/styles.css @@ -0,0 +1,193 @@ +:root{font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif;color:#15243a;background:#f4f7fb;font-synthesis:none;-webkit-font-smoothing:antialiased} +*{box-sizing:border-box} +[hidden]{display:none!important} +body{margin:0;min-width:320px} +button,input,select{font:inherit} +button{cursor:pointer} +button:disabled{cursor:not-allowed;opacity:.52} +input,select{outline:none} +input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px} +.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} +.brand-mark{display:inline-flex;width:34px;height:34px;align-items:center;justify-content:center;border-radius:10px;background:#2ac6ca;box-shadow:0 7px 17px rgba(16,172,184,.18);flex:none} +.brand-mark:before,.brand-mark span{content:"";display:block;width:11px;height:17px;border:3px solid #0c2a3f;transform:skewY(-22deg);border-radius:2px} +.brand-mark:before{border-right:0;margin-right:-1px} +.brand-mark span{border-left:0;margin-left:-1px} +.boot-screen{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;gap:13px;background:#f4f7fb;color:#607087;font-size:14px;z-index:50} +.login-layout{min-height:100vh;display:grid;grid-template-columns:minmax(390px,48%) 1fr;background:#fff} +.login-art{position:relative;min-height:650px;overflow:hidden;background:radial-gradient(circle at 78% 44%,#174c64 0,#122d44 36%,#0d1d31 75%);color:#fff} +.login-art-grid{position:absolute;inset:0;background-image:linear-gradient(rgba(143,221,226,.065) 1px,transparent 1px),linear-gradient(90deg,rgba(143,221,226,.065) 1px,transparent 1px);background-size:50px 50px;mask-image:linear-gradient(90deg,transparent,black)} +.login-art-inner{position:relative;height:100%;min-height:650px;display:flex;flex-direction:column;justify-content:space-between;padding:43px clamp(38px,5vw,90px);z-index:2} +.login-art-brand{display:flex;gap:13px;align-items:center;font-weight:800;font-size:23px;letter-spacing:-.6px} +.login-art-copy{max-width:500px;margin-bottom:70px} +.eyebrow{display:inline-block;color:#159da9;font-size:11px;letter-spacing:.14em;font-weight:800} +.eyebrow.light{color:#53dce0} +.login-art-copy h1{font-size:clamp(38px,4vw,62px);line-height:1.25;letter-spacing:-1.8px;margin:20px 0 19px;font-weight:750} +.login-art-copy p{max-width:380px;color:#bbd1dc;font-size:16px;line-height:1.85;margin:0} +.login-art-footer{color:#bed5dc;font-size:12px;letter-spacing:.04em;display:flex;align-items:center;gap:10px} +.online-dot,.tiny-dot,.connection-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#35d49b;box-shadow:0 0 0 4px rgba(53,212,155,.12)} +.art-orbit{position:absolute;border:1px solid rgba(90,220,220,.19);border-radius:50%;width:560px;height:560px;right:-220px;top:20%;transform:rotate(-28deg)} +.orbit-two{width:390px;height:390px;right:-135px;top:29%;border-color:rgba(90,220,220,.27)} +.art-core{position:absolute;right:5%;top:40%;width:240px;height:240px;transform:rotate(-22deg);opacity:.72} +.art-core span{position:absolute;display:block;border-radius:23px;width:140px;height:140px;border:1px solid rgba(82,220,224,.3);background:linear-gradient(135deg,rgba(75,205,213,.2),rgba(13,35,57,.1));box-shadow:0 25px 55px rgba(0,0,0,.18)} +.art-core span:nth-child(2){top:43px;left:38px}.art-core span:nth-child(3){top:86px;left:76px;background:linear-gradient(135deg,rgba(62,210,210,.42),rgba(9,46,67,.45))} +.login-form-side{display:flex;align-items:center;justify-content:center;padding:40px} +.login-card{width:min(100%,410px)} +.login-mobile-brand{display:none} +.login-card h2{font-size:34px;letter-spacing:-1px;margin:14px 0 8px} +.muted{color:#7a8798;margin:0 0 43px;font-size:14px;line-height:1.7} +.form-stack{display:flex;flex-direction:column} +.form-stack label,.field label,.console-password label{font-size:13px;font-weight:700;color:#34445a;margin:0 0 9px} +.form-stack input,.field input,.field select,.console-password input{height:46px;width:100%;border:1px solid #dce4eb;background:#fff;border-radius:9px;padding:0 13px;color:#15243a;transition:border-color .15s,box-shadow .15s} +.form-stack input:focus,.field input:focus,.field select:focus,.console-password input:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none} +.form-stack input::placeholder,.field input::placeholder{color:#a6b1be} +.form-stack input{margin-bottom:23px} +.form-error{color:#bf3e48;font-size:13px;line-height:1.5;margin:0 0 16px} +.button{border:1px solid transparent;display:inline-flex;align-items:center;justify-content:center;gap:8px;border-radius:9px;padding:10px 17px;min-height:41px;background:#fff;color:#304158;font-size:13px;font-weight:700;white-space:nowrap;transition:transform .15s,box-shadow .15s,background .15s,border-color .15s} +.button:not(:disabled):hover{transform:translateY(-1px)} +.button-primary{background:#0f9eaa;color:#fff;box-shadow:0 8px 17px rgba(15,158,170,.16)} +.button-primary:not(:disabled):hover{background:#0b8c98;box-shadow:0 10px 19px rgba(15,158,170,.22)} +.button-outline{border-color:#d7e0e8;background:#fff;color:#445368} +.button-outline:not(:disabled):hover{border-color:#aebfc8;background:#f8fbfc} +.button-ghost{background:transparent;color:#6a798d} +.button-ghost:not(:disabled):hover{background:#f3f6f9} +.button-danger{background:#d94350;color:#fff} +.button-danger:not(:disabled):hover{background:#c73441} +.button.small{min-height:34px;padding:7px 11px;font-size:12px} +.login-submit{height:48px;justify-content:space-between;padding:0 17px;margin-top:6px;font-size:14px} +.login-submit span{font-size:20px;font-weight:400} +.login-hint{margin:27px 0 0;color:#9aa5b2;font-size:12px;line-height:1.7} +.auth-switch{display:flex;align-items:center;gap:5px;margin:20px 0 0;color:#708093;font-size:12px}.auth-switch button{padding:2px 0;border:0;background:transparent;color:#0f8f9a;font-size:12px;font-weight:800}.auth-switch button:hover{text-decoration:underline}.register-code-row{display:flex;align-items:flex-start;gap:9px;margin-bottom:19px}.register-code-row input{min-width:0;flex:1;margin:0}.register-code-row .button{flex:none;height:46px}.register-code-status,.smtp-status{margin:0 0 16px;padding:10px 12px;border-radius:8px;background:#ecf8f7;color:#267d78;font-size:12px;line-height:1.6}.smtp-status{margin:0}.smtp-card{max-width:780px;margin-bottom:18px}.smtp-card .form-error{margin:0}.pending-users-list{display:grid;gap:10px}.pending-users-list>.muted{margin:0}.pending-user-row{display:flex;align-items:center;justify-content:space-between;gap:15px;border:1px solid #e2ebef;border-radius:9px;padding:13px 15px}.pending-user-details{min-width:0;display:grid;gap:4px;overflow-wrap:anywhere}.pending-user-details strong{font-size:13px;color:#2f455a}.pending-user-details span{font-size:12px;color:#5b7285}.pending-user-details small{font-size:11px;color:#9aabba} +.setup-layout{display:grid;grid-template-columns:minmax(330px,40%) 1fr;min-height:100vh;background:#fff} +.setup-intro{min-height:640px;background:radial-gradient(circle at 90% 95%,#1b5d68,#122d44 40%,#0e1e31 85%);color:#fff;padding:clamp(35px,5vw,75px);display:flex;flex-direction:column;align-items:flex-start} +.setup-brand,.host-brand{display:flex;align-items:center;gap:11px;font-size:22px;font-weight:800;letter-spacing:-.5px}.setup-brand{margin-bottom:auto} +.setup-intro h1{font-size:clamp(40px,4vw,62px);line-height:1.2;margin:18px 0}.setup-intro p{max-width:420px;color:#bed1dc;font-size:15px;line-height:1.85;margin:0 0 47px} +.setup-steps{display:flex;gap:12px;flex-wrap:wrap;width:100%;margin-top:auto}.setup-steps span{padding:10px 15px;border:1px solid #3b596a;border-radius:8px;color:#91aebf;font-size:12px;font-weight:700}.setup-steps .current{background:#1b5260;border-color:#2e8791;color:#6be0df} +.setup-form-side{display:flex;align-items:center;justify-content:center;padding:45px clamp(24px,5vw,80px)}.setup-card{width:min(100%,440px)}.setup-card h2{font-size:31px;letter-spacing:-.8px;margin:13px 0 9px}.setup-card .muted{margin-bottom:29px}.setup-submit{height:47px;justify-content:space-between;margin-top:6px}.setup-submit span{font-size:20px;font-weight:400}.setup-note{font-size:11px;line-height:1.8;color:#9aa8b5;margin:24px 0 0} +.setup-security-note{font-size:11px;line-height:1.75;color:#496372;background:#edf8f8;border:1px solid #d2eeee;border-radius:9px;padding:11px 13px;margin:-10px 0 23px} +.host-layout{min-height:100vh;background:#f4f7fb}.host-topbar{height:75px;background:#fff;border-bottom:1px solid #e7edf2;padding:0 clamp(22px,5vw,76px);display:flex;align-items:center;justify-content:space-between}.host-brand{font-size:20px}.host-topbar-actions{display:flex;align-items:center;gap:14px}.host-user{font-size:12px;color:#65778a;font-weight:700} +.host-content{max-width:1380px;padding:39px clamp(22px,5vw,76px) 70px;margin:0 auto}.host-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;margin-bottom:29px}.host-heading h1{font-size:29px;letter-spacing:-.6px;margin:8px 0}.host-heading p{color:#8090a0;font-size:13px;line-height:1.6;margin:0} +.host-columns{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(350px,.85fr);gap:19px;align-items:start}.host-side-stack{display:grid;gap:19px}.host-card{background:#fff;border:1px solid #e6edf2;border-radius:13px;padding:26px;box-shadow:0 10px 30px rgba(19,42,65,.027)}.host-card-heading{display:flex;gap:12px;align-items:flex-start;margin-bottom:24px}.host-card-number{display:flex;align-items:center;justify-content:center;flex:none;width:31px;height:31px;background:#e7f8f8;color:#0e919b;border-radius:9px;font-size:13px;font-weight:800}.host-card-heading h2{font-size:17px;margin:2px 0 5px;letter-spacing:-.2px}.host-card-heading p{font-size:11px;color:#91a1b0;margin:0;line-height:1.6} +.host-card textarea{width:100%;min-height:125px;padding:12px 13px;border:1px solid #dce4eb;border-radius:9px;color:#15243a;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;resize:vertical;background:#fff}.host-card textarea:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none}.host-card input[type=file]{height:auto;min-height:43px;padding:9px;font-size:11px}.host-card input[type=file]::file-selector-button{border:0;border-radius:6px;padding:5px 10px;margin-right:9px;background:#e9f6f6;color:#137e89;font-weight:700;cursor:pointer} +.host-public-pool{grid-column:1/-1;border-top:1px solid #e8eef2;padding-top:18px}.host-public-pool-heading{margin-bottom:16px}.host-public-pool-heading strong{display:block;color:#34445a;font-size:13px}.host-public-pool-heading small{display:block;margin-top:6px;color:#8798a7;font-size:10px;line-height:1.6}.host-public-pool textarea{min-height:78px} +.fingerprint-result{margin:18px 0 14px;padding:14px;border:1px solid #b9e6e5;background:#effafa;border-radius:9px}.fingerprint-result>span{display:block;color:#417c85;font-size:11px;font-weight:700;margin-bottom:8px}.fingerprint-result code{display:block;color:#1b5260;font-size:12px;font-weight:800;line-height:1.7;overflow-wrap:anywhere}.host-security-note{font-size:11px;color:#8191a1;line-height:1.75;margin:16px 0 0}.host-security-note code{color:#41566e;font-size:10px;overflow-wrap:anywhere}.host-confirm{margin-top:17px;background:#f0fbf8;border-color:#cce9e0}.host-confirm strong{color:#217d6e}.host-confirm small{color:#659a90} +.host-test-status{font-size:12px;color:#708095;background:#f4f7fa;padding:12px 14px;border-radius:8px;line-height:1.55;margin:0 0 15px}.host-test-status.success{background:#e7f8ef;color:#1d9168}.host-test-status.warning{background:#fff4e6;color:#9a641d}.host-submit-actions{display:flex;gap:9px;flex-wrap:wrap}.host-submit-actions .button{flex:1}.host-card .form-error{margin:0 0 13px} +.update-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:19px;align-items:start}.update-grid .host-card{min-width:0}.update-grid .form-stack input{margin-bottom:17px}.update-grid .form-stack .field-hint{display:block;color:#8395a5;font-size:11px;line-height:1.6;margin:-7px 0 17px}.update-grid .form-stack .button{align-self:flex-start}.update-grid .host-test-status{margin-top:17px;overflow-wrap:anywhere}.update-versions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.update-versions>div{border:1px solid #e2ebf0;border-radius:9px;padding:13px;background:#fbfdfd;min-width:0}.update-versions span{display:block;color:#8291a1;font-size:11px;margin-bottom:9px}.update-versions strong{display:block;color:#284459;font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere} +.update-grid .form-stack input[readonly]{background:#f4f7f9;color:#6c7d8d} +.ssh-keys-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);gap:19px;align-items:start}.ssh-keys-grid .host-card{min-width:0}.ssh-keys-grid .form-stack .button{align-self:flex-start}.ssh-keys-grid .form-stack textarea{margin-bottom:19px}.ssh-key-file-hint{display:block;color:#8b9bab;font-size:11px;line-height:1.5;margin:-14px 0 20px}.ssh-keys-list{display:grid;gap:11px}.ssh-keys-list>.muted{margin:0}.ssh-key-row{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:14px;border:1px solid #e2ebef;border-radius:9px;background:#fbfdfd}.ssh-key-details{min-width:0;display:grid;gap:5px}.ssh-key-details strong{font-size:13px;color:#2b4358;overflow-wrap:anywhere}.ssh-key-details code{font-size:11px;color:#3b7a87;overflow-wrap:anywhere}.ssh-key-details small{font-size:10px;color:#95a4b2}.ssh-key-actions{display:flex;flex:none;gap:7px}.ssh-key-delete{color:#b94b57;border-color:#efd8dc} +.ssh-key-picker-title{display:block;color:#34445a;font-size:12px;font-weight:700}.ssh-key-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:10px}.ssh-key-option{display:flex;align-items:center;width:100%;min-width:0;min-height:74px;padding:12px 14px;text-align:left;border:1px solid #dce4eb;border-radius:9px;background:#fff;color:#334a5f;cursor:pointer}.ssh-key-option strong{font-size:12px;line-height:1.5;overflow-wrap:anywhere}.ssh-key-option[aria-pressed="true"]{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.ssh-key-option:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.ssh-key-picker-empty{grid-column:1/-1;margin:0;color:#8b9bab;font-size:11px}.ssh-key-picker-manage{margin-top:9px;padding:0;border:0;background:transparent;color:#148c98;font-size:11px;font-weight:700;cursor:pointer}.ssh-key-picker-manage:hover{text-decoration:underline}.field small.root-password-hint-error{color:#b73e4c}.field small.root-password-hint-success{color:#247f67} +@media(max-width:510px){.ssh-key-picker{grid-template-columns:1fr}} +.unlock-content{min-height:calc(100vh - 75px);display:flex;align-items:center;justify-content:center;padding:40px 24px}.unlock-card{width:min(100%,480px);padding:35px}.unlock-card h1{font-size:28px;letter-spacing:-.5px;margin:12px 0}.unlock-card .muted{margin:0 0 27px}.unlock-card .muted strong{color:#30445a;overflow-wrap:anywhere}.unlock-submit{width:100%;min-height:46px}.unlock-settings-button{margin-top:18px;padding-left:0} +.dashboard{min-height:100vh;display:grid;grid-template-columns:244px minmax(0,1fr)} +.sidebar{position:sticky;top:0;height:100vh;background:#101d2c;color:#d2dce6;padding:32px 15px 22px;display:flex;flex-direction:column} +.sidebar-brand{display:flex;align-items:center;gap:11px;padding:0 13px 46px;font-size:19px;color:#fff;letter-spacing:-.3px;font-weight:800} +.sidebar-brand small{display:block;color:#668197;font-size:8px;letter-spacing:.2em;margin-top:2px} +.sidebar-section-label{color:#64798f;text-transform:uppercase;letter-spacing:.14em;font-size:10px;font-weight:800;margin:0 15px 16px} +.sidebar-link{height:43px;display:flex;align-items:center;gap:13px;padding:0 14px;border-radius:9px;color:#8da2b6;font-size:13px;font-weight:700} +.sidebar-button{width:100%;border:0;background:transparent;text-align:left;font:inherit;cursor:pointer}.sidebar-button:hover{background:#1a3445;color:#d0eeee} +.sidebar-link.active{background:#1d3949;color:#57d4d3} +.nav-icon{font-size:20px;line-height:1}.nav-arrow{margin-left:auto;font-size:20px;opacity:.7} +.sidebar-bottom{margin-top:auto} +.host-panel{display:flex;align-items:center;gap:10px;padding:14px 11px;border:1px solid #274050;border-radius:10px;background:#172c3e} +.host-panel-icon{width:31px;height:31px;border-radius:8px;background:#213e4e;color:#5fd4d1;display:flex;align-items:center;justify-content:center;font-size:20px} +.host-panel strong,.host-panel span{display:block}.host-panel strong{font-size:11px;color:#dce8ec}.host-panel div:nth-child(2) span{font-size:10px;color:#8ca6b6;margin-top:3px} +.host-panel .connection-dot{margin-left:auto;width:7px;height:7px;box-shadow:none;flex:none}.host-panel .connection-dot.offline{background:#e68a7d} +.sidebar-caption{font-size:10px;color:#577086;margin:20px 10px 0;letter-spacing:.06em} +.main-area{min-width:0} +.topbar{height:74px;background:#fff;border-bottom:1px solid #e7edf2;display:flex;align-items:center;justify-content:space-between;padding:0 clamp(24px,3.3vw,55px)} +.breadcrumb{font-size:12px;color:#8c9bac}.breadcrumb span{padding:0 11px;color:#bbc5d0}.breadcrumb strong{color:#344961;font-weight:700} +.topbar-right{display:flex;align-items:center;gap:19px}.topbar-user{display:flex;align-items:center;gap:9px;color:#34455b;font-size:12px;font-weight:700} +.host-settings-mobile{display:none} +.admin-menu{display:none;position:relative;z-index:11}.admin-menu summary{list-style:none;display:flex;align-items:center;gap:5px;min-height:32px;padding:5px 9px;border-radius:7px;color:#536b7e;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.admin-menu summary::-webkit-details-marker{display:none}.admin-menu summary:hover,.admin-menu[open] summary{background:#edf6f6;color:#117f88}.admin-menu-options{position:absolute;right:0;top:calc(100% + 5px);display:grid;gap:3px;min-width:148px;padding:6px;border:1px solid #dde7ed;border-radius:9px;background:#fff;box-shadow:0 12px 30px rgba(17,42,59,.14)}.admin-menu-options .button{width:100%;justify-content:flex-start} +.avatar{display:inline-flex;align-items:center;justify-content:center;border-radius:50%;height:30px;width:30px;background:#e9f8f7;color:#118e9a;font-size:12px;font-weight:800} +.content{max-width:1600px;margin:0 auto;padding:37px clamp(24px,3.3vw,55px) 24px} +.page-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin-bottom:32px} +.page-heading h1{font-size:28px;letter-spacing:-.6px;margin:9px 0 8px}.page-heading p{margin:0;color:#8390a2;font-size:13px} +.resource-warning{margin:-11px 0 23px;padding:13px 16px;border:1px solid #f0d8aa;border-radius:9px;background:#fff8eb;color:#916323;font-size:12px;line-height:1.65;overflow-wrap:anywhere} +.heading-actions{display:flex;gap:10px;padding-bottom:3px} +.overview-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:17px;margin-bottom:25px} +.stat-card{min-height:148px;padding:22px 24px;background:#fff;border:1px solid #e9eef3;border-radius:13px;box-shadow:0 9px 27px rgba(18,47,71,.025)} +.stat-top{display:flex;align-items:center;justify-content:space-between;color:#79889a;font-size:12px;font-weight:700} +.stat-icon{display:flex;align-items:center;justify-content:center;width:33px;height:33px;border-radius:9px;font-size:16px} +.stat-icon.total{background:#e9f4fb;color:#4387b4}.stat-icon.running{background:#e7f9f1;color:#27b07c}.stat-icon.stopped{background:#f0f1f7;color:#8191a9} +.stat-card>strong{display:block;font-size:32px;line-height:1.1;margin-top:14px;letter-spacing:-1px}.stat-card>small{display:flex;align-items:center;gap:9px;color:#a2acb8;font-size:11px;margin-top:10px}.tiny-dot{width:6px;height:6px;box-shadow:none}.tiny-dot.green{background:#39c78e} +.inventory-panel{background:#fff;border:1px solid #e7ecf2;border-radius:13px;box-shadow:0 10px 30px rgba(19,42,65,.027);min-height:390px} +.panel-heading{display:flex;justify-content:space-between;gap:20px;align-items:center;padding:23px 25px 20px;border-bottom:1px solid #edf1f5} +.panel-heading h2{font-size:17px;letter-spacing:-.2px;margin:0 0 6px}.panel-heading p{color:#9aa6b3;font-size:11px;margin:0} +.panel-tools{display:flex;gap:9px}.search-box{position:relative;display:flex;align-items:center}.search-box>span:first-child{position:absolute;left:12px;color:#9aa8b8;font-size:19px;line-height:1} +.search-box input,.panel-tools select{height:37px;border:1px solid #e0e6ec;border-radius:8px;background:#fff;color:#516075;font-size:12px} +.search-box input{width:220px;padding:0 12px 0 34px}.search-box input::placeholder{color:#a4afbb}.panel-tools select{padding:0 29px 0 11px} +.table-scroll{overflow-x:auto;min-height:100px} +table{border-collapse:collapse;width:100%;min-width:850px}.vm-table{min-width:1060px}.vm-table th,.vm-table td{padding-left:15px;padding-right:15px} +thead{background:#fbfcfe}th{height:47px;text-align:left;font-size:10px;letter-spacing:.05em;color:#9ba8b7;text-transform:uppercase;font-weight:800;padding:0 24px} +th.actions-heading{text-align:right;padding-right:28px} +td{height:83px;border-top:1px solid #edf1f5;padding:15px 24px;font-size:12px;color:#607087} +tbody tr:hover{background:#fcfefe} +.vm-identity{display:flex;align-items:center;gap:12px;min-width:160px}.vm-icon{width:38px;height:38px;border-radius:10px;background:#e9f8f8;color:#239eaa;display:flex;align-items:center;justify-content:center;font-size:19px;flex:none}.vm-name{display:block;color:#25384e;font-size:13px;font-weight:800;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-uuid-row{display:flex;align-items:center;gap:5px;margin-top:6px;max-width:265px}.vm-id{display:block;min-width:0;color:#a6b1bf;font-size:10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-uuid-row .vm-copy-icon{width:21px;min-height:21px;padding:2px}.vm-uuid-row .vm-copy-icon svg{width:13px;height:13px} +.vm-public-ip{display:block;color:#16868f;font-size:10px;font-weight:700;margin-top:5px;white-space:nowrap} +.vm-name-link{display:block;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;padding:2px 0;color:#25384e;font-size:13px;font-weight:800;text-align:left;text-decoration:underline;text-decoration-color:transparent;text-underline-offset:3px;cursor:pointer}.vm-name-link:not(:disabled):hover,.vm-name-link:not(:disabled):focus-visible{color:#118e98;text-decoration-color:currentColor}.vm-metadata{display:block;max-width:205px;color:#53647a;line-height:1.5;overflow-wrap:anywhere}.vm-ip{color:#16868f;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;white-space:nowrap} +.state-pill{display:inline-flex;align-items:center;gap:7px;padding:6px 9px;border-radius:6px;font-size:11px;font-weight:800;background:#f1f3f6;color:#758499;white-space:nowrap}.state-pill:before{content:"";width:6px;height:6px;background:currentColor;border-radius:50%}.state-pill.running{background:#e7f8ef;color:#20a46f}.state-pill.stopped{background:#f2f4f7;color:#8290a3}.state-pill.other{background:#fff4e5;color:#b98129} +.vm-spec{color:#53647a;white-space:nowrap}.vm-spec strong{color:#283a50;font-weight:700}.vm-spec small{display:block;color:#a2aeb9;font-size:10px;margin-top:5px} +.row-actions{display:flex;align-items:center;justify-content:flex-end;gap:5px;white-space:nowrap}.row-button{border:1px solid transparent;background:transparent;color:#577083;border-radius:7px;padding:7px 8px;min-height:31px;font-size:11px;font-weight:700}.row-button:not(:disabled):hover{background:#e8f7f7;color:#117f88}.row-button.primary{background:#e7f7f7;color:#118e98}.row-button.danger{color:#bf6470}.row-button.danger:not(:disabled):hover{background:#fff0f1;color:#ba3a49} +.empty-state{text-align:center;padding:65px 20px 72px}.empty-icon{margin:0 auto 16px;width:54px;height:54px;display:flex;align-items:center;justify-content:center;border-radius:16px;background:#eaf7f7;color:#17a3aa;font-size:28px}.empty-state h3{font-size:16px;color:#34465a;margin:0 0 8px}.empty-state p{font-size:12px;color:#a0aebe;margin:0} +.footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px} +.vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-summary{display:flex;align-items:center;flex-wrap:wrap;gap:5px 18px}.vm-detail-summary span{white-space:nowrap}.vm-detail-summary strong{color:#455a70;font-weight:700;margin-left:4px}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef} +.vm-detail-inline,.vm-ip-copy-row{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.vm-detail-inline{min-height:25px}.vm-detail-secret{font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-mini-button,.vm-copy-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;border:1px solid #d9e9ea;border-radius:6px;background:#f5fbfb;color:#1b8790;font-size:11px;font-weight:700;min-height:25px;padding:3px 7px}.vm-detail-mini-button:not(:disabled):hover,.vm-copy-icon:not(:disabled):hover{background:#e6f6f7;border-color:#b6dcdf}.vm-copy-icon{width:25px;padding:3px}.vm-copy-icon svg{display:block;width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} +.vm-credential-icon{width:30px;min-height:30px}.vm-credential-icon svg{width:17px;height:17px}.vm-credential-icon .vm-eye-slash{visibility:hidden}.vm-credential-icon[aria-pressed="true"] .vm-eye-slash{visibility:visible} +.vm-detail-facts .vm-detail-credential-row{grid-column:1/-1} +.vm-metrics{margin-top:25px}.vm-metrics-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}.vm-metrics-heading h2{font-size:19px;margin:7px 0 6px}.vm-metrics-heading p{font-size:11px;color:#8191a1;line-height:1.6;margin:0}.vm-metrics-range-control{display:flex;align-items:center;gap:9px;flex:none;color:#64768a;font-size:11px;font-weight:700}.vm-metrics-range-control select{height:37px;padding:0 11px;border:1px solid #dbe6ec;border-radius:8px;color:#344e60;background:#fff;font-size:12px;font-weight:700}.vm-metrics-status{margin:0 0 14px;padding:9px 12px;border-radius:8px;background:#eaf7f7;color:#277b82;font-size:11px;line-height:1.5}.vm-metrics-status.warning{background:#fff6e9;color:#946620}.vm-metrics-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-metric-card{min-width:0;padding:20px 21px 16px;border:1px solid #e7ecf2;border-radius:13px;background:#fff;box-shadow:0 10px 30px rgba(19,42,65,.027)}.vm-metric-card-heading{display:flex;align-items:flex-start;gap:11px;min-height:62px}.vm-metric-card-heading>div{min-width:0}.vm-metric-card-heading h3{margin:1px 0 6px;font-size:13px;color:#32485b}.vm-metric-card-heading p{margin:0;color:#60758a;font-size:12px;line-height:1.45;overflow-wrap:anywhere}.vm-metric-icon{display:flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;border-radius:9px;font-size:18px;font-weight:700}.vm-metric-icon.cpu{background:#e8f8f8;color:#0f9eaa}.vm-metric-icon.memory{background:#edf3fb;color:#4781cf}.vm-metric-icon.disk{background:#eef3fa;color:#477dc9}.vm-metric-icon.network{background:#eaf8f2;color:#17a685}.vm-metric-plot{display:flex;align-items:center;justify-content:center;height:205px;margin:8px 0 6px;overflow:hidden}.vm-metric-plot svg{display:block;width:100%;height:100%;font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif}.vm-metric-gridline{stroke:#e5edf2;stroke-width:1;stroke-dasharray:3 4}.vm-metric-axis-label{fill:#9aabb9;font-size:10px}.vm-metric-empty{margin:0;padding:15px;text-align:center;color:#94a2af;font-size:11px;line-height:1.6}.vm-metric-legend{display:flex;align-items:center;flex-wrap:wrap;gap:15px;padding-left:7px;color:#728297;font-size:10px;font-weight:700}.vm-metric-legend span{display:inline-flex;align-items:center;gap:6px}.vm-metric-swatch{display:inline-block;width:16px;height:0;border-top:3px solid #0f9eaa;border-radius:2px}.vm-metric-swatch.cpu{border-color:#0f9eaa}.vm-metric-swatch.memory{border-color:#4781cf}.vm-metric-swatch.memory-total{border-color:#a4b7d7;border-top-style:dashed}.vm-metric-swatch.disk-read{border-color:#477dc9}.vm-metric-swatch.disk-write{border-color:#e59c46}.vm-metric-swatch.network-rx{border-color:#17a685}.vm-metric-swatch.network-tx{border-color:#926ed0}.vm-metrics-footnote{margin:12px 1px 0;color:#9ba8b6;font-size:10px;line-height:1.6} +.modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)} +.modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)} +.modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:26px 29px 18px;border-bottom:1px solid #edf1f5}.modal-header h2{font-size:21px;letter-spacing:-.35px;margin:7px 0 5px}.modal-header p{font-size:12px;color:#95a1af;margin:0}.icon-button{border:0;border-radius:8px;background:transparent;color:#8a98a8;width:31px;height:31px;font-size:23px;line-height:1;display:flex;align-items:center;justify-content:center}.icon-button:hover{background:#f1f5f8;color:#30445a} +.modal-body{padding:23px 29px 25px}.modal-footer{display:flex;justify-content:flex-end;gap:9px;padding:18px 29px;border-top:1px solid #edf1f5} +.workspace-form-page{width:min(100%,900px);margin:0 auto 48px}.workspace-form-back{padding-left:0;margin-bottom:15px;min-height:34px}.workspace-form-heading{margin-bottom:22px}.workspace-form-heading h1{margin-top:8px}.workspace-form-card{overflow:hidden}.workspace-form-body{padding:28px clamp(22px,3vw,36px) 32px}.workspace-form-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:10px;padding:18px clamp(22px,3vw,36px);border-top:1px solid #edf1f5;background:#fbfdfe}.workspace-form-actions .button{min-width:120px}.workspace-form-body>.form-error{margin:18px 0 0} +.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 17px}.field.full{grid-column:1/-1}.field label{display:block}.field label span{color:#dc5965}.field small{display:block;color:#a1adbb;font-size:10px;margin-top:7px;line-height:1.5}.field select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2393a1ae' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:35px} +.create-source-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;border:0;padding:0;margin:0 0 23px;min-width:0}.create-source-picker legend{color:#34445a;font-size:13px;font-weight:700;padding:0;margin-bottom:10px}.create-source-picker label{position:relative;display:block;cursor:pointer}.create-source-picker input{position:absolute;opacity:0;width:1px;height:1px}.create-source-picker label span{display:block;border:1px solid #dce4eb;border-radius:9px;padding:12px 14px;min-height:65px;background:#fff}.create-source-picker input:checked+span{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.create-source-picker input:focus-visible+span{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.create-source-picker strong{display:block;color:#334a5f;font-size:12px}.create-source-picker small{display:block;color:#8999a8;font-size:10px;margin-top:5px} +.template-field-label{display:block;color:#34445a;font-size:13px;font-weight:700;margin-bottom:10px}.template-field-label span{color:#dc5965}.template-catalog{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:14px}.template-catalog-empty{grid-column:1/-1;margin:0;padding:17px;border:1px dashed #cbdbe3;border-radius:10px;background:#f8fbfc;color:#698094;font-size:12px}.template-family-card{min-width:0;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden}.template-family-card[open]{border-color:#46b6ba;box-shadow:0 0 0 2px rgba(20,166,175,.07)}.template-family-summary{display:flex;align-items:center;flex-direction:column;gap:9px;min-height:153px;padding:20px 13px 13px;cursor:pointer;text-align:center;list-style:none}.template-family-summary::-webkit-details-marker{display:none}.template-family-summary:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:-3px}.template-family-summary strong{color:#30465a;font-size:13px}.template-family-icon{display:flex;align-items:center;justify-content:center;width:65px;height:65px;border-radius:17px;background:linear-gradient(145deg,#2a6385,#173d58);color:#fff;font-size:31px;font-weight:800;box-shadow:0 6px 16px rgba(24,68,90,.15)}.template-family-arrow{color:#258f9b;font-size:20px;line-height:1;transition:transform .2s}.template-family-card[open] .template-family-arrow{transform:rotate(180deg)}.template-versions{display:grid;gap:7px;padding:12px;border-top:1px solid #e7edf2;background:#fbfdfd}.template-version-option{width:100%;display:grid;gap:3px;padding:11px 12px;border:1px solid #dee8ed;border-radius:8px;background:#fff;text-align:left;color:#344e60}.template-version-option strong{font-size:12px}.template-version-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)}.template-version-option:hover{border-color:#48b6bd}.template-admin-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);align-items:start;gap:19px}.template-admin-grid .host-card{min-width:0}.template-admin-grid .form-stack .button{align-self:flex-start}.template-field-help{display:block;margin:-16px 0 19px;color:#8b9bab;font-size:11px;line-height:1.55}.template-import-status{margin:0 0 14px;padding:10px 12px;border-radius:8px;background:#edf8f8;color:#317c85;font-size:11px;line-height:1.6}.template-admin-list{display:grid;gap:10px}.template-admin-list>.muted{margin:0}.template-admin-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:9px 11px;align-items:end;padding:14px;border:1px solid #e0e9ee;border-radius:10px;background:#fbfdfd}.template-admin-row-heading{grid-column:1/-1;display:flex;align-items:center;gap:9px;margin-bottom:3px;color:#34495c;font-size:12px}.template-admin-icon{display:flex;align-items:center;justify-content:center;width:27px;height:27px;border-radius:7px;background:#e3f6f3;color:#138d8f;font-weight:800}.template-admin-row label{grid-column:1/-1;margin:0;color:#75899b;font-size:11px;font-weight:700}.template-admin-row input{width:100%;min-width:0;height:37px;padding:0 10px;border:1px solid #dce4eb;border-radius:7px;background:#fff;color:#20364a;font-size:12px}.template-admin-row .button{min-height:37px}.template-admin-row .form-error{grid-column:1/-1;margin:0} +.template-family-icon.system,.template-admin-icon.system{background:transparent;border:0;box-shadow:none;color:inherit;text-shadow:none}.template-system-logo{display:block;width:100%;height:100%;object-fit:contain}.template-version-option{display:flex;align-items:center;justify-content:center;text-align:center}.template-version-option strong{overflow-wrap:anywhere} +.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px} +.vm-auto-public-pool{display:grid;gap:5px;margin:0 0 18px;padding:13px 15px;border:1px solid #cce9e0;border-radius:9px;background:#f0fbf8}.vm-auto-public-pool strong{font-size:12px;color:#217d6e}.vm-auto-public-pool span{font-size:11px;line-height:1.6;color:#5b837a}.vm-cloud-auth-fields{margin-top:18px} +.input-suffix{position:relative}.input-suffix input{padding-right:48px}.input-suffix span{position:absolute;right:13px;top:13px;color:#97a4b2;font-size:12px} +.form-tip{display:flex;gap:10px;background:#f1f9fa;border:1px solid #e1f2f3;border-radius:9px;padding:12px 14px;color:#318b96;margin-top:22px}.form-tip>span{font-size:16px;line-height:1}.form-tip p{font-size:11px;line-height:1.55;margin:0}.modal-body>.form-error{margin:18px 0 0} +.delete-copy{font-size:13px;color:#647388;line-height:1.8;margin:0 0 19px}.delete-copy strong{color:#263c54;overflow-wrap:anywhere}.danger-text{color:#d64753} +.reinstall-warning{margin:0 0 15px;padding:14px 16px;border:1px solid #f2cbd0;border-radius:9px;background:#fff4f5;color:#99414d;font-size:12px;line-height:1.7}.reinstall-warning strong{display:block;margin-bottom:4px;color:#a82f3f;font-size:13px}.reinstall-network{margin:0 0 21px;color:#51677c;font-size:12px;line-height:1.7}.reinstall-network strong{color:#174458;overflow-wrap:anywhere} +.reinstall-progress{display:flex;align-items:flex-start;gap:15px;padding:14px 2px;min-height:105px}.reinstall-progress .console-spinner{flex:none;margin-top:2px}.reinstall-progress strong{display:block;color:#274459;font-size:14px}.reinstall-progress p{margin:8px 0;color:#238894;font-size:12px;line-height:1.6}.reinstall-progress small{display:block;color:#8192a4;font-size:11px;line-height:1.6} +.reinstall-result{padding:4px 0 10px}.reinstall-result h3{margin:0 0 10px;color:#167f72;font-size:18px}.reinstall-result.failed h3{color:#b1404c}.reinstall-result.unknown h3{color:#916425}.reinstall-result>p{margin:0 0 14px;color:#4f6478;font-size:12px;line-height:1.75;overflow-wrap:anywhere}.reinstall-password-box{border:1px solid #b9e2d5;border-radius:9px;background:#f1fbf7;padding:14px;margin-top:15px}.reinstall-password-box>span{display:block;color:#286f60;font-size:12px;font-weight:700}.reinstall-password-box>div{display:flex;align-items:center;gap:9px;margin:10px 0}.reinstall-password-box code{display:block;flex:1;min-width:0;padding:11px;border-radius:7px;background:#fff;color:#1d4a41;font-size:14px;overflow-wrap:anywhere;user-select:all}.reinstall-password-box small{display:block;color:#617f76;font-size:11px;line-height:1.6}.reinstall-result-warning{padding:10px 12px;border-radius:8px;background:#fff6e7;color:#916425!important} +.checkbox-row{border:1px solid #f0dadd;background:#fffafa;border-radius:9px;padding:14px;display:flex;align-items:flex-start;gap:11px;cursor:pointer}.checkbox-row input{margin:3px 0 0;accent-color:#d94350}.checkbox-row strong{display:block;font-size:12px;color:#9e3440}.checkbox-row small{display:block;margin-top:4px;font-size:11px;line-height:1.5;color:#bd7a81} +.console-backdrop{padding:24px}.console-modal{width:min(100%,1200px);max-height:95vh;display:flex;flex-direction:column;overflow:hidden;background:#101820}.console-toolbar{display:flex;align-items:center;justify-content:space-between;gap:20px;background:#fff;padding:15px 20px}.console-toolbar h2{margin:4px 0 1px;font-size:16px}.console-toolbar p{margin:0;font-size:11px;color:#93a1af}.console-tools{display:flex;align-items:center;gap:8px}.console-stage{position:relative;min-height:280px;height:min(70vh,720px);background:#101820;display:flex;align-items:center;justify-content:center;overflow:hidden}.console-stage canvas{max-width:100%;max-height:100%}.console-placeholder{display:flex;align-items:center;gap:13px;color:#a9b9c5;font-size:12px}.console-spinner{height:20px;width:20px;border-radius:50%;border:2px solid #4f6673;border-top-color:#40ccd0;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.console-password{display:flex;align-items:center;gap:10px;background:#fff;padding:13px 20px}.console-password label{margin:0;white-space:nowrap}.console-password input{width:220px;height:35px} +.toast-region{position:fixed;right:23px;bottom:22px;display:flex;flex-direction:column;gap:9px;z-index:80;pointer-events:none}.toast{max-width:min(430px,calc(100vw - 36px));padding:12px 16px;border-radius:9px;color:#fff;background:#20364a;box-shadow:0 10px 24px rgba(15,30,44,.2);font-size:12px;line-height:1.5;pointer-events:auto}.toast.error{background:#ae3c49}.toast.success{background:#157e75} +@media(max-width:1150px){th,td{padding-left:15px;padding-right:15px}.row-button{padding:6px}.content{padding-left:28px;padding-right:28px}} +@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.admin-menu{display:block}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}} +@media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}} +@media(max-width:960px){.update-grid{grid-template-columns:1fr}} +@media(max-width:960px){.template-admin-grid{grid-template-columns:1fr}} +@media(max-width:960px){.ssh-keys-grid{grid-template-columns:1fr}} +@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}} +@media(max-width:740px){.vm-metrics-grid{grid-template-columns:1fr}.vm-metrics-heading{align-items:flex-start;flex-direction:column}.vm-metric-plot{height:190px}} +@media(max-width:740px){.login-layout{display:block;min-height:100vh}.login-art{display:none}.login-form-side{min-height:100vh;padding:32px 25px}.login-mobile-brand{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:800;margin-bottom:70px}.login-card h2{font-size:29px}.page-heading{align-items:flex-start;flex-direction:column;gap:20px}.heading-actions{width:100%}.heading-actions .button{flex:1}.overview-grid{gap:9px}.stat-card{min-height:121px;padding:16px}.stat-card>strong{font-size:25px}.stat-top{font-size:10px}.stat-icon{width:27px;height:27px;font-size:12px}.stat-card>small{font-size:9px}.panel-heading{align-items:flex-start;flex-direction:column;padding:19px}.panel-tools{width:100%}.search-box{flex:1}.search-box input{width:100%}.footer-note{text-align:left}.console-toolbar{align-items:flex-start}.console-tools{flex-wrap:wrap;justify-content:flex-end}.console-tools .button{font-size:10px}} +@media(max-width:740px){.vm-table{min-width:0}.vm-table thead{display:none}.vm-table tbody{display:grid;gap:12px;padding:12px}.vm-table tr{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid #e4ebf0;border-radius:10px;overflow:hidden}.vm-table td{display:block;min-width:0;height:auto;border:0;padding:12px 14px}.vm-table td:first-child{grid-column:1/-1;border-bottom:1px solid #edf1f5}.vm-table td:not(:first-child):before{content:attr(data-label);display:block;color:#9ba8b7;font-size:10px;font-weight:800;margin-bottom:7px}.vm-table .vm-metadata{max-width:none}.vm-table .vm-ip{white-space:normal}.vm-detail-facts{padding:4px 17px 12px}.vm-detail-actions{padding:16px 19px 19px}} +@media(max-width:740px){.setup-layout{display:block}.setup-intro{min-height:0;padding:28px 25px}.setup-brand{margin:0 0 38px}.setup-intro h1{font-size:31px;margin:11px 0}.setup-intro p{font-size:12px;margin-bottom:24px}.setup-steps{margin-top:0}.setup-form-side{padding:36px 25px 55px}.setup-card h2{font-size:27px}.host-side-stack{grid-template-columns:1fr}.host-heading{align-items:flex-start;flex-direction:column}.host-topbar{height:65px}.host-content{padding-top:27px}.host-card{padding:20px}} +@media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}} +@media(max-width:510px){.topbar-right{flex-wrap:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.update-versions{grid-template-columns:1fr}} +@media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.template-catalog{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.template-family-summary{min-height:137px;padding:16px 9px 11px}.template-family-icon{width:55px;height:55px;font-size:27px}.template-versions{padding:8px}.template-version-option{padding:9px 8px}.template-admin-row{grid-template-columns:1fr}.template-admin-row .button{justify-self:start}} +@media(max-width:510px){.workspace-form-body{padding:22px 19px 25px}.workspace-form-actions{padding:15px 19px}.workspace-form-actions .button{flex:1 1 100%}.workspace-form-back{margin-bottom:10px}} +@media(max-width:510px){.host-public-pool>.form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.ssh-key-row{align-items:flex-start;flex-direction:column}.ssh-key-actions{width:100%}.ssh-key-actions .button{flex:1}} +@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}} +.rescue-status{margin:8px 0 17px;padding:12px 14px;border:1px solid #c8e9e8;border-radius:9px;background:#f0fbfa;color:#236d71;font-size:12px;line-height:1.6} +.rescue-directory-note{margin:0 0 17px;padding:10px 12px;border:1px solid #d6e8ee;border-radius:8px;background:#f6fafc;color:#557085;font-size:11px;line-height:1.6;overflow-wrap:anywhere} +.rescue-login-note{margin:0 0 19px;color:#557085;font-size:12px;line-height:1.7} +#rescue-status-title{margin:0;color:#2c465a;font-size:16px} +.rescue-template-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin:0 0 21px} +.rescue-template-card{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;min-height:130px;padding:16px 13px;border:1px solid #dce7ec;border-radius:11px;background:#fff;color:#314b5c;text-align:center;cursor:pointer;overflow-wrap:anywhere} +.rescue-template-card:hover,.rescue-template-card:focus-visible{border-color:#38aeb7;outline:none;box-shadow:0 0 0 3px rgba(25,179,187,.1)} +.rescue-template-card[aria-pressed="true"]{border-color:#28a8b0;background:#eaf8f8;box-shadow:0 0 0 2px rgba(25,179,187,.12)} +.rescue-template-card:disabled{cursor:wait;opacity:.7} +.rescue-template-symbol{display:grid;place-items:center;width:43px;height:43px;border-radius:10px;background:#e2f6f5;color:#168d94;font-size:24px;font-weight:800} +.rescue-template-card strong{font-size:12px}.rescue-template-card small{font-size:11px;color:#8798a5} +.rescue-actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:12px}.rescue-actions .button{min-width:190px} +.rescue-template-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 14px;border:1px solid #e0e9ee;border-radius:9px;background:#fbfdfd} +.rescue-template-row-label{display:grid;gap:5px;min-width:0;overflow-wrap:anywhere}.rescue-template-row-label strong{font-size:12px;color:#34495c}.rescue-template-row-label small{font-size:11px;color:#8a9caa} +#rescue-template-file{height:auto;padding:10px 12px} +@media(max-width:510px){.rescue-template-cards{grid-template-columns:repeat(2,minmax(0,1fr))}.rescue-actions .button{width:100%}.rescue-template-row{align-items:flex-start;flex-direction:column}} diff --git a/web/public/cloud/ubuntu-icon.svg b/web/public/cloud/ubuntu-icon.svg new file mode 100644 index 00000000..89b79e94 --- /dev/null +++ b/web/public/cloud/ubuntu-icon.svg @@ -0,0 +1 @@ + diff --git a/web/public/cloud/vendor/novnc/LICENSE.txt b/web/public/cloud/vendor/novnc/LICENSE.txt new file mode 100644 index 00000000..0581c11e --- /dev/null +++ b/web/public/cloud/vendor/novnc/LICENSE.txt @@ -0,0 +1,62 @@ +noVNC is Copyright (C) 2022 The noVNC authors +(./AUTHORS) + +The noVNC core library files are licensed under the MPL 2.0 (Mozilla +Public License 2.0). The noVNC core library is composed of the +Javascript code necessary for full noVNC operation. This includes (but +is not limited to): + + core/**/*.js + app/*.js + test/playback.js + +The HTML, CSS, font and images files that included with the noVNC +source distibution (or repository) are not considered part of the +noVNC core library and are licensed under more permissive licenses. +The intent is to allow easy integration of noVNC into existing web +sites and web applications. + +The HTML, CSS, font and image files are licensed as follows: + + *.html : 2-Clause BSD license + + app/styles/*.css : 2-Clause BSD license + + app/styles/Orbitron* : SIL Open Font License 1.1 + (Copyright 2009 Matt McInerney) + + app/images/ : Creative Commons Attribution-ShareAlike + http://creativecommons.org/licenses/by-sa/3.0/ + +Some portions of noVNC are copyright to their individual authors. +Please refer to the individual source files and/or to the noVNC commit +history: https://github.com/novnc/noVNC/commits/master + +The are several files and projects that have been incorporated into +the noVNC core library. Here is a list of those files and the original +licenses (all MPL 2.0 compatible): + + core/base64.js : MPL 2.0 + + core/des.js : Various BSD style licenses + + vendor/pako/ : MIT + +Any other files not mentioned above are typically marked with +a copyright/license header at the top of the file. The default noVNC +license is MPL-2.0. + +The following license texts are included: + + docs/LICENSE.MPL-2.0 + docs/LICENSE.OFL-1.1 + docs/LICENSE.BSD-3-Clause (New BSD) + docs/LICENSE.BSD-2-Clause (Simplified BSD / FreeBSD) + vendor/pako/LICENSE (MIT) + +Or alternatively the license texts may be found here: + + http://www.mozilla.org/MPL/2.0/ + http://scripts.sil.org/OFL + http://en.wikipedia.org/wiki/BSD_licenses + https://opensource.org/licenses/MIT diff --git a/web/public/cloud/vendor/novnc/core/base64.js b/web/public/cloud/vendor/novnc/core/base64.js new file mode 100644 index 00000000..db572c2d --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/base64.js @@ -0,0 +1,104 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// From: http://hg.mozilla.org/mozilla-central/raw-file/ec10630b1a54/js/src/devtools/jint/sunspider/string-base64.js + +import * as Log from './util/logging.js'; + +export default { + /* Convert data (an array of integers) to a Base64 string. */ + toBase64Table: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''), + base64Pad: '=', + + encode(data) { + "use strict"; + let result = ''; + const length = data.length; + const lengthpad = (length % 3); + // Convert every three bytes to 4 ascii characters. + + for (let i = 0; i < (length - 2); i += 3) { + result += this.toBase64Table[data[i] >> 2]; + result += this.toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)]; + result += this.toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)]; + result += this.toBase64Table[data[i + 2] & 0x3f]; + } + + // Convert the remaining 1 or 2 bytes, pad out to 4 characters. + const j = length - lengthpad; + if (lengthpad === 2) { + result += this.toBase64Table[data[j] >> 2]; + result += this.toBase64Table[((data[j] & 0x03) << 4) + (data[j + 1] >> 4)]; + result += this.toBase64Table[(data[j + 1] & 0x0f) << 2]; + result += this.toBase64Table[64]; + } else if (lengthpad === 1) { + result += this.toBase64Table[data[j] >> 2]; + result += this.toBase64Table[(data[j] & 0x03) << 4]; + result += this.toBase64Table[64]; + result += this.toBase64Table[64]; + } + + return result; + }, + + /* Convert Base64 data to a string */ + /* eslint-disable comma-spacing */ + toBinaryTable: [ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 + ], + /* eslint-enable comma-spacing */ + + decode(data, offset = 0) { + let dataLength = data.indexOf('=') - offset; + if (dataLength < 0) { dataLength = data.length - offset; } + + /* Every four characters is 3 resulting numbers */ + const resultLength = (dataLength >> 2) * 3 + Math.floor((dataLength % 4) / 1.5); + const result = new Array(resultLength); + + // Convert one by one. + + let leftbits = 0; // number of bits decoded, but yet to be appended + let leftdata = 0; // bits decoded, but yet to be appended + for (let idx = 0, i = offset; i < data.length; i++) { + const c = this.toBinaryTable[data.charCodeAt(i) & 0x7f]; + const padding = (data.charAt(i) === this.base64Pad); + // Skip illegal characters and whitespace + if (c === -1) { + Log.Error("Illegal character code " + data.charCodeAt(i) + " at position " + i); + continue; + } + + // Collect data into leftdata, update bitcount + leftdata = (leftdata << 6) | c; + leftbits += 6; + + // If we have 8 or more bits, append 8 bits to the result + if (leftbits >= 8) { + leftbits -= 8; + // Append if not padding. + if (!padding) { + result[idx++] = (leftdata >> leftbits) & 0xff; + } + leftdata &= (1 << leftbits) - 1; + } + } + + // If there are any bits left, the base64 string was corrupted + if (leftbits) { + const err = new Error('Corrupted base64 string'); + err.name = 'Base64-Error'; + throw err; + } + + return result; + } +}; /* End of Base64 namespace */ diff --git a/web/public/cloud/vendor/novnc/core/crypto/aes.js b/web/public/cloud/vendor/novnc/core/crypto/aes.js new file mode 100644 index 00000000..e6aaea7c --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/crypto/aes.js @@ -0,0 +1,178 @@ +export class AESECBCipher { + constructor() { + this._key = null; + } + + get algorithm() { + return { name: "AES-ECB" }; + } + + static async importKey(key, _algorithm, extractable, keyUsages) { + const cipher = new AESECBCipher; + await cipher._importKey(key, extractable, keyUsages); + return cipher; + } + + async _importKey(key, extractable, keyUsages) { + this._key = await window.crypto.subtle.importKey( + "raw", key, {name: "AES-CBC"}, extractable, keyUsages); + } + + async encrypt(_algorithm, plaintext) { + const x = new Uint8Array(plaintext); + if (x.length % 16 !== 0 || this._key === null) { + return null; + } + const n = x.length / 16; + for (let i = 0; i < n; i++) { + const y = new Uint8Array(await window.crypto.subtle.encrypt({ + name: "AES-CBC", + iv: new Uint8Array(16), + }, this._key, x.slice(i * 16, i * 16 + 16))).slice(0, 16); + x.set(y, i * 16); + } + return x; + } +} + +export class AESEAXCipher { + constructor() { + this._rawKey = null; + this._ctrKey = null; + this._cbcKey = null; + this._zeroBlock = new Uint8Array(16); + this._prefixBlock0 = this._zeroBlock; + this._prefixBlock1 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + this._prefixBlock2 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]); + } + + get algorithm() { + return { name: "AES-EAX" }; + } + + async _encryptBlock(block) { + const encrypted = await window.crypto.subtle.encrypt({ + name: "AES-CBC", + iv: this._zeroBlock, + }, this._cbcKey, block); + return new Uint8Array(encrypted).slice(0, 16); + } + + async _initCMAC() { + const k1 = await this._encryptBlock(this._zeroBlock); + const k2 = new Uint8Array(16); + const v = k1[0] >>> 6; + for (let i = 0; i < 15; i++) { + k2[i] = (k1[i + 1] >> 6) | (k1[i] << 2); + k1[i] = (k1[i + 1] >> 7) | (k1[i] << 1); + } + const lut = [0x0, 0x87, 0x0e, 0x89]; + k2[14] ^= v >>> 1; + k2[15] = (k1[15] << 2) ^ lut[v]; + k1[15] = (k1[15] << 1) ^ lut[v >> 1]; + this._k1 = k1; + this._k2 = k2; + } + + async _encryptCTR(data, counter) { + const encrypted = await window.crypto.subtle.encrypt({ + name: "AES-CTR", + counter: counter, + length: 128 + }, this._ctrKey, data); + return new Uint8Array(encrypted); + } + + async _decryptCTR(data, counter) { + const decrypted = await window.crypto.subtle.decrypt({ + name: "AES-CTR", + counter: counter, + length: 128 + }, this._ctrKey, data); + return new Uint8Array(decrypted); + } + + async _computeCMAC(data, prefixBlock) { + if (prefixBlock.length !== 16) { + return null; + } + const n = Math.floor(data.length / 16); + const m = Math.ceil(data.length / 16); + const r = data.length - n * 16; + const cbcData = new Uint8Array((m + 1) * 16); + cbcData.set(prefixBlock); + cbcData.set(data, 16); + if (r === 0) { + for (let i = 0; i < 16; i++) { + cbcData[n * 16 + i] ^= this._k1[i]; + } + } else { + cbcData[(n + 1) * 16 + r] = 0x80; + for (let i = 0; i < 16; i++) { + cbcData[(n + 1) * 16 + i] ^= this._k2[i]; + } + } + let cbcEncrypted = await window.crypto.subtle.encrypt({ + name: "AES-CBC", + iv: this._zeroBlock, + }, this._cbcKey, cbcData); + + cbcEncrypted = new Uint8Array(cbcEncrypted); + const mac = cbcEncrypted.slice(cbcEncrypted.length - 32, cbcEncrypted.length - 16); + return mac; + } + + static async importKey(key, _algorithm, _extractable, _keyUsages) { + const cipher = new AESEAXCipher; + await cipher._importKey(key); + return cipher; + } + + async _importKey(key) { + this._rawKey = key; + this._ctrKey = await window.crypto.subtle.importKey( + "raw", key, {name: "AES-CTR"}, false, ["encrypt", "decrypt"]); + this._cbcKey = await window.crypto.subtle.importKey( + "raw", key, {name: "AES-CBC"}, false, ["encrypt"]); + await this._initCMAC(); + } + + async encrypt(algorithm, message) { + const ad = algorithm.additionalData; + const nonce = algorithm.iv; + const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0); + const encrypted = await this._encryptCTR(message, nCMAC); + const adCMAC = await this._computeCMAC(ad, this._prefixBlock1); + const mac = await this._computeCMAC(encrypted, this._prefixBlock2); + for (let i = 0; i < 16; i++) { + mac[i] ^= nCMAC[i] ^ adCMAC[i]; + } + const res = new Uint8Array(16 + encrypted.length); + res.set(encrypted); + res.set(mac, encrypted.length); + return res; + } + + async decrypt(algorithm, data) { + const encrypted = data.slice(0, data.length - 16); + const ad = algorithm.additionalData; + const nonce = algorithm.iv; + const mac = data.slice(data.length - 16); + const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0); + const adCMAC = await this._computeCMAC(ad, this._prefixBlock1); + const computedMac = await this._computeCMAC(encrypted, this._prefixBlock2); + for (let i = 0; i < 16; i++) { + computedMac[i] ^= nCMAC[i] ^ adCMAC[i]; + } + if (computedMac.length !== mac.length) { + return null; + } + for (let i = 0; i < mac.length; i++) { + if (computedMac[i] !== mac[i]) { + return null; + } + } + const res = await this._decryptCTR(encrypted, nCMAC); + return res; + } +} diff --git a/web/public/cloud/vendor/novnc/core/crypto/bigint.js b/web/public/cloud/vendor/novnc/core/crypto/bigint.js new file mode 100644 index 00000000..d3443265 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/crypto/bigint.js @@ -0,0 +1,34 @@ +export function modPow(b, e, m) { + let r = 1n; + b = b % m; + while (e > 0n) { + if ((e & 1n) === 1n) { + r = (r * b) % m; + } + e = e >> 1n; + b = (b * b) % m; + } + return r; +} + +export function bigIntToU8Array(bigint, padLength=0) { + let hex = bigint.toString(16); + if (padLength === 0) { + padLength = Math.ceil(hex.length / 2); + } + hex = hex.padStart(padLength * 2, '0'); + const length = hex.length / 2; + const arr = new Uint8Array(length); + for (let i = 0; i < length; i++) { + arr[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); + } + return arr; +} + +export function u8ArrayToBigInt(arr) { + let hex = '0x'; + for (let i = 0; i < arr.length; i++) { + hex += arr[i].toString(16).padStart(2, '0'); + } + return BigInt(hex); +} diff --git a/web/public/cloud/vendor/novnc/core/crypto/crypto.js b/web/public/cloud/vendor/novnc/core/crypto/crypto.js new file mode 100644 index 00000000..cc17da22 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/crypto/crypto.js @@ -0,0 +1,90 @@ +import { AESECBCipher, AESEAXCipher } from "./aes.js"; +import { DESCBCCipher, DESECBCipher } from "./des.js"; +import { RSACipher } from "./rsa.js"; +import { DHCipher } from "./dh.js"; +import { MD5 } from "./md5.js"; + +// A single interface for the cryptographic algorithms not supported by SubtleCrypto. +// Both synchronous and asynchronous implmentations are allowed. +class LegacyCrypto { + constructor() { + this._algorithms = { + "AES-ECB": AESECBCipher, + "AES-EAX": AESEAXCipher, + "DES-ECB": DESECBCipher, + "DES-CBC": DESCBCCipher, + "RSA-PKCS1-v1_5": RSACipher, + "DH": DHCipher, + "MD5": MD5, + }; + } + + encrypt(algorithm, key, data) { + if (key.algorithm.name !== algorithm.name) { + throw new Error("algorithm does not match"); + } + if (typeof key.encrypt !== "function") { + throw new Error("key does not support encryption"); + } + return key.encrypt(algorithm, data); + } + + decrypt(algorithm, key, data) { + if (key.algorithm.name !== algorithm.name) { + throw new Error("algorithm does not match"); + } + if (typeof key.decrypt !== "function") { + throw new Error("key does not support encryption"); + } + return key.decrypt(algorithm, data); + } + + importKey(format, keyData, algorithm, extractable, keyUsages) { + if (format !== "raw") { + throw new Error("key format is not supported"); + } + const alg = this._algorithms[algorithm.name]; + if (typeof alg === "undefined" || typeof alg.importKey !== "function") { + throw new Error("algorithm is not supported"); + } + return alg.importKey(keyData, algorithm, extractable, keyUsages); + } + + generateKey(algorithm, extractable, keyUsages) { + const alg = this._algorithms[algorithm.name]; + if (typeof alg === "undefined" || typeof alg.generateKey !== "function") { + throw new Error("algorithm is not supported"); + } + return alg.generateKey(algorithm, extractable, keyUsages); + } + + exportKey(format, key) { + if (format !== "raw") { + throw new Error("key format is not supported"); + } + if (typeof key.exportKey !== "function") { + throw new Error("key does not support exportKey"); + } + return key.exportKey(); + } + + digest(algorithm, data) { + const alg = this._algorithms[algorithm]; + if (typeof alg !== "function") { + throw new Error("algorithm is not supported"); + } + return alg(data); + } + + deriveBits(algorithm, key, length) { + if (key.algorithm.name !== algorithm.name) { + throw new Error("algorithm does not match"); + } + if (typeof key.deriveBits !== "function") { + throw new Error("key does not support deriveBits"); + } + return key.deriveBits(algorithm, length); + } +} + +export default new LegacyCrypto; diff --git a/web/public/cloud/vendor/novnc/core/crypto/des.js b/web/public/cloud/vendor/novnc/core/crypto/des.js new file mode 100644 index 00000000..8dab31fb --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/crypto/des.js @@ -0,0 +1,330 @@ +/* + * Ported from Flashlight VNC ActionScript implementation: + * http://www.wizhelp.com/flashlight-vnc/ + * + * Full attribution follows: + * + * ------------------------------------------------------------------------- + * + * This DES class has been extracted from package Acme.Crypto for use in VNC. + * The unnecessary odd parity code has been removed. + * + * These changes are: + * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. + * + * This software 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. + * + + * DesCipher - the DES encryption method + * + * The meat of this code is by Dave Zimmerman , and is: + * + * Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved. + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and + * without fee is hereby granted, provided that this copyright notice is kept + * intact. + * + * WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY + * OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED + * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE + * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. + * + * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE + * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE + * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT + * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE + * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE + * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE + * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP + * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR + * HIGH RISK ACTIVITIES. + * + * + * The rest is: + * + * Copyright (C) 1996 by Jef Poskanzer . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * Visit the ACME Labs Java page for up-to-date versions of this and other + * fine Java utilities: http://www.acme.com/java/ + */ + +/* eslint-disable comma-spacing */ + +// Tables, permutations, S-boxes, etc. +const PC2 = [13,16,10,23, 0, 4, 2,27,14, 5,20, 9,22,18,11, 3, + 25, 7,15, 6,26,19,12, 1,40,51,30,36,46,54,29,39, + 50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31 ], + totrot = [ 1, 2, 4, 6, 8,10,12,14,15,17,19,21,23,25,27,28]; + +const z = 0x0; +let a,b,c,d,e,f; +a=1<<16; b=1<<24; c=a|b; d=1<<2; e=1<<10; f=d|e; +const SP1 = [c|e,z|z,a|z,c|f,c|d,a|f,z|d,a|z,z|e,c|e,c|f,z|e,b|f,c|d,b|z,z|d, + z|f,b|e,b|e,a|e,a|e,c|z,c|z,b|f,a|d,b|d,b|d,a|d,z|z,z|f,a|f,b|z, + a|z,c|f,z|d,c|z,c|e,b|z,b|z,z|e,c|d,a|z,a|e,b|d,z|e,z|d,b|f,a|f, + c|f,a|d,c|z,b|f,b|d,z|f,a|f,c|e,z|f,b|e,b|e,z|z,a|d,a|e,z|z,c|d]; +a=1<<20; b=1<<31; c=a|b; d=1<<5; e=1<<15; f=d|e; +const SP2 = [c|f,b|e,z|e,a|f,a|z,z|d,c|d,b|f,b|d,c|f,c|e,b|z,b|e,a|z,z|d,c|d, + a|e,a|d,b|f,z|z,b|z,z|e,a|f,c|z,a|d,b|d,z|z,a|e,z|f,c|e,c|z,z|f, + z|z,a|f,c|d,a|z,b|f,c|z,c|e,z|e,c|z,b|e,z|d,c|f,a|f,z|d,z|e,b|z, + z|f,c|e,a|z,b|d,a|d,b|f,b|d,a|d,a|e,z|z,b|e,z|f,b|z,c|d,c|f,a|e]; +a=1<<17; b=1<<27; c=a|b; d=1<<3; e=1<<9; f=d|e; +const SP3 = [z|f,c|e,z|z,c|d,b|e,z|z,a|f,b|e,a|d,b|d,b|d,a|z,c|f,a|d,c|z,z|f, + b|z,z|d,c|e,z|e,a|e,c|z,c|d,a|f,b|f,a|e,a|z,b|f,z|d,c|f,z|e,b|z, + c|e,b|z,a|d,z|f,a|z,c|e,b|e,z|z,z|e,a|d,c|f,b|e,b|d,z|e,z|z,c|d, + b|f,a|z,b|z,c|f,z|d,a|f,a|e,b|d,c|z,b|f,z|f,c|z,a|f,z|d,c|d,a|e]; +a=1<<13; b=1<<23; c=a|b; d=1<<0; e=1<<7; f=d|e; +const SP4 = [c|d,a|f,a|f,z|e,c|e,b|f,b|d,a|d,z|z,c|z,c|z,c|f,z|f,z|z,b|e,b|d, + z|d,a|z,b|z,c|d,z|e,b|z,a|d,a|e,b|f,z|d,a|e,b|e,a|z,c|e,c|f,z|f, + b|e,b|d,c|z,c|f,z|f,z|z,z|z,c|z,a|e,b|e,b|f,z|d,c|d,a|f,a|f,z|e, + c|f,z|f,z|d,a|z,b|d,a|d,c|e,b|f,a|d,a|e,b|z,c|d,z|e,b|z,a|z,c|e]; +a=1<<25; b=1<<30; c=a|b; d=1<<8; e=1<<19; f=d|e; +const SP5 = [z|d,a|f,a|e,c|d,z|e,z|d,b|z,a|e,b|f,z|e,a|d,b|f,c|d,c|e,z|f,b|z, + a|z,b|e,b|e,z|z,b|d,c|f,c|f,a|d,c|e,b|d,z|z,c|z,a|f,a|z,c|z,z|f, + z|e,c|d,z|d,a|z,b|z,a|e,c|d,b|f,a|d,b|z,c|e,a|f,b|f,z|d,a|z,c|e, + c|f,z|f,c|z,c|f,a|e,z|z,b|e,c|z,z|f,a|d,b|d,z|e,z|z,b|e,a|f,b|d]; +a=1<<22; b=1<<29; c=a|b; d=1<<4; e=1<<14; f=d|e; +const SP6 = [b|d,c|z,z|e,c|f,c|z,z|d,c|f,a|z,b|e,a|f,a|z,b|d,a|d,b|e,b|z,z|f, + z|z,a|d,b|f,z|e,a|e,b|f,z|d,c|d,c|d,z|z,a|f,c|e,z|f,a|e,c|e,b|z, + b|e,z|d,c|d,a|e,c|f,a|z,z|f,b|d,a|z,b|e,b|z,z|f,b|d,c|f,a|e,c|z, + a|f,c|e,z|z,c|d,z|d,z|e,c|z,a|f,z|e,a|d,b|f,z|z,c|e,b|z,a|d,b|f]; +a=1<<21; b=1<<26; c=a|b; d=1<<1; e=1<<11; f=d|e; +const SP7 = [a|z,c|d,b|f,z|z,z|e,b|f,a|f,c|e,c|f,a|z,z|z,b|d,z|d,b|z,c|d,z|f, + b|e,a|f,a|d,b|e,b|d,c|z,c|e,a|d,c|z,z|e,z|f,c|f,a|e,z|d,b|z,a|e, + b|z,a|e,a|z,b|f,b|f,c|d,c|d,z|d,a|d,b|z,b|e,a|z,c|e,z|f,a|f,c|e, + z|f,b|d,c|f,c|z,a|e,z|z,z|d,c|f,z|z,a|f,c|z,z|e,b|d,b|e,z|e,a|d]; +a=1<<18; b=1<<28; c=a|b; d=1<<6; e=1<<12; f=d|e; +const SP8 = [b|f,z|e,a|z,c|f,b|z,b|f,z|d,b|z,a|d,c|z,c|f,a|e,c|e,a|f,z|e,z|d, + c|z,b|d,b|e,z|f,a|e,a|d,c|d,c|e,z|f,z|z,z|z,c|d,b|d,b|e,a|f,a|z, + a|f,a|z,c|e,z|e,z|d,c|d,z|e,a|f,b|e,z|d,b|d,c|z,c|d,b|z,a|z,b|f, + z|z,c|f,a|d,b|d,c|z,b|e,b|f,z|z,c|f,a|e,a|e,z|f,z|f,a|d,b|z,c|e]; + +/* eslint-enable comma-spacing */ + +class DES { + constructor(password) { + this.keys = []; + + // Set the key. + const pc1m = [], pcr = [], kn = []; + + for (let j = 0, l = 56; j < 56; ++j, l -= 8) { + l += l < -5 ? 65 : l < -3 ? 31 : l < -1 ? 63 : l === 27 ? 35 : 0; // PC1 + const m = l & 0x7; + pc1m[j] = ((password[l >>> 3] & (1<>> 10; + this.keys[KnLi] |= (raw1 & 0x00000fc0) >>> 6; + ++KnLi; + this.keys[KnLi] = (raw0 & 0x0003f000) << 12; + this.keys[KnLi] |= (raw0 & 0x0000003f) << 16; + this.keys[KnLi] |= (raw1 & 0x0003f000) >>> 4; + this.keys[KnLi] |= (raw1 & 0x0000003f); + ++KnLi; + } + } + + // Encrypt 8 bytes of text + enc8(text) { + const b = text.slice(); + let i = 0, l, r, x; // left, right, accumulator + + // Squash 8 bytes to 2 ints + l = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++]; + r = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++]; + + x = ((l >>> 4) ^ r) & 0x0f0f0f0f; + r ^= x; + l ^= (x << 4); + x = ((l >>> 16) ^ r) & 0x0000ffff; + r ^= x; + l ^= (x << 16); + x = ((r >>> 2) ^ l) & 0x33333333; + l ^= x; + r ^= (x << 2); + x = ((r >>> 8) ^ l) & 0x00ff00ff; + l ^= x; + r ^= (x << 8); + r = (r << 1) | ((r >>> 31) & 1); + x = (l ^ r) & 0xaaaaaaaa; + l ^= x; + r ^= x; + l = (l << 1) | ((l >>> 31) & 1); + + for (let i = 0, keysi = 0; i < 8; ++i) { + x = (r << 28) | (r >>> 4); + x ^= this.keys[keysi++]; + let fval = SP7[x & 0x3f]; + fval |= SP5[(x >>> 8) & 0x3f]; + fval |= SP3[(x >>> 16) & 0x3f]; + fval |= SP1[(x >>> 24) & 0x3f]; + x = r ^ this.keys[keysi++]; + fval |= SP8[x & 0x3f]; + fval |= SP6[(x >>> 8) & 0x3f]; + fval |= SP4[(x >>> 16) & 0x3f]; + fval |= SP2[(x >>> 24) & 0x3f]; + l ^= fval; + x = (l << 28) | (l >>> 4); + x ^= this.keys[keysi++]; + fval = SP7[x & 0x3f]; + fval |= SP5[(x >>> 8) & 0x3f]; + fval |= SP3[(x >>> 16) & 0x3f]; + fval |= SP1[(x >>> 24) & 0x3f]; + x = l ^ this.keys[keysi++]; + fval |= SP8[x & 0x0000003f]; + fval |= SP6[(x >>> 8) & 0x3f]; + fval |= SP4[(x >>> 16) & 0x3f]; + fval |= SP2[(x >>> 24) & 0x3f]; + r ^= fval; + } + + r = (r << 31) | (r >>> 1); + x = (l ^ r) & 0xaaaaaaaa; + l ^= x; + r ^= x; + l = (l << 31) | (l >>> 1); + x = ((l >>> 8) ^ r) & 0x00ff00ff; + r ^= x; + l ^= (x << 8); + x = ((l >>> 2) ^ r) & 0x33333333; + r ^= x; + l ^= (x << 2); + x = ((r >>> 16) ^ l) & 0x0000ffff; + l ^= x; + r ^= (x << 16); + x = ((r >>> 4) ^ l) & 0x0f0f0f0f; + l ^= x; + r ^= (x << 4); + + // Spread ints to bytes + x = [r, l]; + for (i = 0; i < 8; i++) { + b[i] = (x[i>>>2] >>> (8 * (3 - (i % 4)))) % 256; + if (b[i] < 0) { b[i] += 256; } // unsigned + } + return b; + } +} + +export class DESECBCipher { + constructor() { + this._cipher = null; + } + + get algorithm() { + return { name: "DES-ECB" }; + } + + static importKey(key, _algorithm, _extractable, _keyUsages) { + const cipher = new DESECBCipher; + cipher._importKey(key); + return cipher; + } + + _importKey(key, _extractable, _keyUsages) { + this._cipher = new DES(key); + } + + encrypt(_algorithm, plaintext) { + const x = new Uint8Array(plaintext); + if (x.length % 8 !== 0 || this._cipher === null) { + return null; + } + const n = x.length / 8; + for (let i = 0; i < n; i++) { + x.set(this._cipher.enc8(x.slice(i * 8, i * 8 + 8)), i * 8); + } + return x; + } +} + +export class DESCBCCipher { + constructor() { + this._cipher = null; + } + + get algorithm() { + return { name: "DES-CBC" }; + } + + static importKey(key, _algorithm, _extractable, _keyUsages) { + const cipher = new DESCBCCipher; + cipher._importKey(key); + return cipher; + } + + _importKey(key) { + this._cipher = new DES(key); + } + + encrypt(algorithm, plaintext) { + const x = new Uint8Array(plaintext); + let y = new Uint8Array(algorithm.iv); + if (x.length % 8 !== 0 || this._cipher === null) { + return null; + } + const n = x.length / 8; + for (let i = 0; i < n; i++) { + for (let j = 0; j < 8; j++) { + y[j] ^= plaintext[i * 8 + j]; + } + y = this._cipher.enc8(y); + x.set(y, i * 8); + } + return x; + } +} diff --git a/web/public/cloud/vendor/novnc/core/crypto/dh.js b/web/public/cloud/vendor/novnc/core/crypto/dh.js new file mode 100644 index 00000000..bd705d9b --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/crypto/dh.js @@ -0,0 +1,55 @@ +import { modPow, bigIntToU8Array, u8ArrayToBigInt } from "./bigint.js"; + +class DHPublicKey { + constructor(key) { + this._key = key; + } + + get algorithm() { + return { name: "DH" }; + } + + exportKey() { + return this._key; + } +} + +export class DHCipher { + constructor() { + this._g = null; + this._p = null; + this._gBigInt = null; + this._pBigInt = null; + this._privateKey = null; + } + + get algorithm() { + return { name: "DH" }; + } + + static generateKey(algorithm, _extractable) { + const cipher = new DHCipher; + cipher._generateKey(algorithm); + return { privateKey: cipher, publicKey: new DHPublicKey(cipher._publicKey) }; + } + + _generateKey(algorithm) { + const g = algorithm.g; + const p = algorithm.p; + this._keyBytes = p.length; + this._gBigInt = u8ArrayToBigInt(g); + this._pBigInt = u8ArrayToBigInt(p); + this._privateKey = window.crypto.getRandomValues(new Uint8Array(this._keyBytes)); + this._privateKeyBigInt = u8ArrayToBigInt(this._privateKey); + this._publicKey = bigIntToU8Array(modPow( + this._gBigInt, this._privateKeyBigInt, this._pBigInt), this._keyBytes); + } + + deriveBits(algorithm, length) { + const bytes = Math.ceil(length / 8); + const pkey = new Uint8Array(algorithm.public); + const len = bytes > this._keyBytes ? bytes : this._keyBytes; + const secret = modPow(u8ArrayToBigInt(pkey), this._privateKeyBigInt, this._pBigInt); + return bigIntToU8Array(secret, len).slice(0, len); + } +} diff --git a/web/public/cloud/vendor/novnc/core/crypto/md5.js b/web/public/cloud/vendor/novnc/core/crypto/md5.js new file mode 100644 index 00000000..b01ba6fd --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/crypto/md5.js @@ -0,0 +1,82 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2021 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * Performs MD5 hashing on an array of bytes, returns an array of bytes + */ + +export async function MD5(d) { + let s = ""; + for (let i = 0; i < d.length; i++) { + s += String.fromCharCode(d[i]); + } + return M(V(Y(X(s), 8 * s.length))); +} + +function M(d) { + let f = new Uint8Array(d.length); + for (let i=0;i> 2); + for (let m = 0; m < r.length; m++) r[m] = 0; + for (let m = 0; m < 8 * d.length; m += 8) r[m >> 5] |= (255 & d.charCodeAt(m / 8)) << m % 32; + return r; +} + +function V(d) { + let r = ""; + for (let m = 0; m < 32 * d.length; m += 8) r += String.fromCharCode(d[m >> 5] >>> m % 32 & 255); + return r; +} + +function Y(d, g) { + d[g >> 5] |= 128 << g % 32, d[14 + (g + 64 >>> 9 << 4)] = g; + let m = 1732584193, f = -271733879, r = -1732584194, i = 271733878; + for (let n = 0; n < d.length; n += 16) { + let h = m, + t = f, + g = r, + e = i; + f = ii(f = ii(f = ii(f = ii(f = hh(f = hh(f = hh(f = hh(f = gg(f = gg(f = gg(f = gg(f = ff(f = ff(f = ff(f = ff(f, r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 0], 7, -680876936), f, r, d[n + 1], 12, -389564586), m, f, d[n + 2], 17, 606105819), i, m, d[n + 3], 22, -1044525330), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 4], 7, -176418897), f, r, d[n + 5], 12, 1200080426), m, f, d[n + 6], 17, -1473231341), i, m, d[n + 7], 22, -45705983), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 8], 7, 1770035416), f, r, d[n + 9], 12, -1958414417), m, f, d[n + 10], 17, -42063), i, m, d[n + 11], 22, -1990404162), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 12], 7, 1804603682), f, r, d[n + 13], 12, -40341101), m, f, d[n + 14], 17, -1502002290), i, m, d[n + 15], 22, 1236535329), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 1], 5, -165796510), f, r, d[n + 6], 9, -1069501632), m, f, d[n + 11], 14, 643717713), i, m, d[n + 0], 20, -373897302), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 5], 5, -701558691), f, r, d[n + 10], 9, 38016083), m, f, d[n + 15], 14, -660478335), i, m, d[n + 4], 20, -405537848), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 9], 5, 568446438), f, r, d[n + 14], 9, -1019803690), m, f, d[n + 3], 14, -187363961), i, m, d[n + 8], 20, 1163531501), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 13], 5, -1444681467), f, r, d[n + 2], 9, -51403784), m, f, d[n + 7], 14, 1735328473), i, m, d[n + 12], 20, -1926607734), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 5], 4, -378558), f, r, d[n + 8], 11, -2022574463), m, f, d[n + 11], 16, 1839030562), i, m, d[n + 14], 23, -35309556), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 1], 4, -1530992060), f, r, d[n + 4], 11, 1272893353), m, f, d[n + 7], 16, -155497632), i, m, d[n + 10], 23, -1094730640), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 13], 4, 681279174), f, r, d[n + 0], 11, -358537222), m, f, d[n + 3], 16, -722521979), i, m, d[n + 6], 23, 76029189), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 9], 4, -640364487), f, r, d[n + 12], 11, -421815835), m, f, d[n + 15], 16, 530742520), i, m, d[n + 2], 23, -995338651), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 0], 6, -198630844), f, r, d[n + 7], 10, 1126891415), m, f, d[n + 14], 15, -1416354905), i, m, d[n + 5], 21, -57434055), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 12], 6, 1700485571), f, r, d[n + 3], 10, -1894986606), m, f, d[n + 10], 15, -1051523), i, m, d[n + 1], 21, -2054922799), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 8], 6, 1873313359), f, r, d[n + 15], 10, -30611744), m, f, d[n + 6], 15, -1560198380), i, m, d[n + 13], 21, 1309151649), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 4], 6, -145523070), f, r, d[n + 11], 10, -1120210379), m, f, d[n + 2], 15, 718787259), i, m, d[n + 9], 21, -343485551), m = add(m, h), f = add(f, t), r = add(r, g), i = add(i, e); + } + return Array(m, f, r, i); +} + +function cmn(d, g, m, f, r, i) { + return add(rol(add(add(g, d), add(f, i)), r), m); +} + +function ff(d, g, m, f, r, i, n) { + return cmn(g & m | ~g & f, d, g, r, i, n); +} + +function gg(d, g, m, f, r, i, n) { + return cmn(g & f | m & ~f, d, g, r, i, n); +} + +function hh(d, g, m, f, r, i, n) { + return cmn(g ^ m ^ f, d, g, r, i, n); +} + +function ii(d, g, m, f, r, i, n) { + return cmn(m ^ (g | ~f), d, g, r, i, n); +} + +function add(d, g) { + let m = (65535 & d) + (65535 & g); + return (d >> 16) + (g >> 16) + (m >> 16) << 16 | 65535 & m; +} + +function rol(d, g) { + return d << g | d >>> 32 - g; +} diff --git a/web/public/cloud/vendor/novnc/core/crypto/rsa.js b/web/public/cloud/vendor/novnc/core/crypto/rsa.js new file mode 100644 index 00000000..68e8e869 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/crypto/rsa.js @@ -0,0 +1,132 @@ +import Base64 from "../base64.js"; +import { modPow, bigIntToU8Array, u8ArrayToBigInt } from "./bigint.js"; + +export class RSACipher { + constructor() { + this._keyLength = 0; + this._keyBytes = 0; + this._n = null; + this._e = null; + this._d = null; + this._nBigInt = null; + this._eBigInt = null; + this._dBigInt = null; + this._extractable = false; + } + + get algorithm() { + return { name: "RSA-PKCS1-v1_5" }; + } + + _base64urlDecode(data) { + data = data.replace(/-/g, "+").replace(/_/g, "/"); + data = data.padEnd(Math.ceil(data.length / 4) * 4, "="); + return Base64.decode(data); + } + + _padArray(arr, length) { + const res = new Uint8Array(length); + res.set(arr, length - arr.length); + return res; + } + + static async generateKey(algorithm, extractable, _keyUsages) { + const cipher = new RSACipher; + await cipher._generateKey(algorithm, extractable); + return { privateKey: cipher }; + } + + async _generateKey(algorithm, extractable) { + this._keyLength = algorithm.modulusLength; + this._keyBytes = Math.ceil(this._keyLength / 8); + const key = await window.crypto.subtle.generateKey( + { + name: "RSA-OAEP", + modulusLength: algorithm.modulusLength, + publicExponent: algorithm.publicExponent, + hash: {name: "SHA-256"}, + }, + true, ["encrypt", "decrypt"]); + const privateKey = await window.crypto.subtle.exportKey("jwk", key.privateKey); + this._n = this._padArray(this._base64urlDecode(privateKey.n), this._keyBytes); + this._nBigInt = u8ArrayToBigInt(this._n); + this._e = this._padArray(this._base64urlDecode(privateKey.e), this._keyBytes); + this._eBigInt = u8ArrayToBigInt(this._e); + this._d = this._padArray(this._base64urlDecode(privateKey.d), this._keyBytes); + this._dBigInt = u8ArrayToBigInt(this._d); + this._extractable = extractable; + } + + static async importKey(key, _algorithm, extractable, keyUsages) { + if (keyUsages.length !== 1 || keyUsages[0] !== "encrypt") { + throw new Error("only support importing RSA public key"); + } + const cipher = new RSACipher; + await cipher._importKey(key, extractable); + return cipher; + } + + async _importKey(key, extractable) { + const n = key.n; + const e = key.e; + if (n.length !== e.length) { + throw new Error("the sizes of modulus and public exponent do not match"); + } + this._keyBytes = n.length; + this._keyLength = this._keyBytes * 8; + this._n = new Uint8Array(this._keyBytes); + this._e = new Uint8Array(this._keyBytes); + this._n.set(n); + this._e.set(e); + this._nBigInt = u8ArrayToBigInt(this._n); + this._eBigInt = u8ArrayToBigInt(this._e); + this._extractable = extractable; + } + + async encrypt(_algorithm, message) { + if (message.length > this._keyBytes - 11) { + return null; + } + const ps = new Uint8Array(this._keyBytes - message.length - 3); + window.crypto.getRandomValues(ps); + for (let i = 0; i < ps.length; i++) { + ps[i] = Math.floor(ps[i] * 254 / 255 + 1); + } + const em = new Uint8Array(this._keyBytes); + em[1] = 0x02; + em.set(ps, 2); + em.set(message, ps.length + 3); + const emBigInt = u8ArrayToBigInt(em); + const c = modPow(emBigInt, this._eBigInt, this._nBigInt); + return bigIntToU8Array(c, this._keyBytes); + } + + async decrypt(_algorithm, message) { + if (message.length !== this._keyBytes) { + return null; + } + const msgBigInt = u8ArrayToBigInt(message); + const emBigInt = modPow(msgBigInt, this._dBigInt, this._nBigInt); + const em = bigIntToU8Array(emBigInt, this._keyBytes); + if (em[0] !== 0x00 || em[1] !== 0x02) { + return null; + } + let i = 2; + for (; i < em.length; i++) { + if (em[i] === 0x00) { + break; + } + } + if (i === em.length) { + return null; + } + return em.slice(i + 1, em.length); + } + + async exportKey() { + if (!this._extractable) { + throw new Error("key is not extractable"); + } + return { n: this._n, e: this._e, d: this._d }; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/copyrect.js b/web/public/cloud/vendor/novnc/core/decoders/copyrect.js new file mode 100644 index 00000000..3c7e0d5d --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/copyrect.js @@ -0,0 +1,27 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class CopyRectDecoder { + decodeRect(x, y, width, height, sock, display, depth) { + if (sock.rQwait("COPYRECT", 4)) { + return false; + } + + let deltaX = sock.rQshift16(); + let deltaY = sock.rQshift16(); + + if ((width === 0) || (height === 0)) { + return true; + } + + display.copyImage(deltaX, deltaY, x, y, width, height); + + return true; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/h264.js b/web/public/cloud/vendor/novnc/core/decoders/h264.js new file mode 100644 index 00000000..a508b674 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/h264.js @@ -0,0 +1,321 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2024 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import * as Log from '../util/logging.js'; + +export class H264Parser { + constructor(data) { + this._data = data; + this._index = 0; + this.profileIdc = null; + this.constraintSet = null; + this.levelIdc = null; + } + + _getStartSequenceLen(index) { + let data = this._data; + if (data[index + 0] == 0 && data[index + 1] == 0 && data[index + 2] == 0 && data[index + 3] == 1) { + return 4; + } + if (data[index + 0] == 0 && data[index + 1] == 0 && data[index + 2] == 1) { + return 3; + } + return 0; + } + + _indexOfNextNalUnit(index) { + let data = this._data; + for (let i = index; i < data.length; ++i) { + if (this._getStartSequenceLen(i) != 0) { + return i; + } + } + return -1; + } + + _parseSps(index) { + this.profileIdc = this._data[index]; + this.constraintSet = this._data[index + 1]; + this.levelIdc = this._data[index + 2]; + } + + _parseNalUnit(index) { + const firstByte = this._data[index]; + if (firstByte & 0x80) { + throw new Error('H264 parsing sanity check failed, forbidden zero bit is set'); + } + const unitType = firstByte & 0x1f; + + switch (unitType) { + case 1: // coded slice, non-idr + return { slice: true }; + case 5: // coded slice, idr + return { slice: true, key: true }; + case 6: // sei + return {}; + case 7: // sps + this._parseSps(index + 1); + return {}; + case 8: // pps + return {}; + default: + Log.Warn("Unhandled unit type: ", unitType); + break; + } + return {}; + } + + parse() { + const startIndex = this._index; + let isKey = false; + + while (this._index < this._data.length) { + const startSequenceLen = this._getStartSequenceLen(this._index); + if (startSequenceLen == 0) { + throw new Error('Invalid start sequence in bit stream'); + } + + const { slice, key } = this._parseNalUnit(this._index + startSequenceLen); + + let nextIndex = this._indexOfNextNalUnit(this._index + startSequenceLen); + if (nextIndex == -1) { + this._index = this._data.length; + } else { + this._index = nextIndex; + } + + if (key) { + isKey = true; + } + if (slice) { + break; + } + } + + if (startIndex === this._index) { + return null; + } + + return { + frame: this._data.subarray(startIndex, this._index), + key: isKey, + }; + } +} + +export class H264Context { + constructor(width, height) { + this.lastUsed = 0; + this._width = width; + this._height = height; + this._profileIdc = null; + this._constraintSet = null; + this._levelIdc = null; + this._decoder = null; + this._pendingFrames = []; + } + + _handleFrame(frame) { + let pending = this._pendingFrames.shift(); + if (pending === undefined) { + throw new Error("Pending frame queue empty when receiving frame from decoder"); + } + + if (pending.timestamp != frame.timestamp) { + throw new Error("Video frame timestamp mismatch. Expected " + + frame.timestamp + " but but got " + pending.timestamp); + } + + pending.frame = frame; + pending.ready = true; + pending.resolve(); + + if (!pending.keep) { + frame.close(); + } + } + + _handleError(e) { + throw new Error("Failed to decode frame: " + e.message); + } + + _configureDecoder(profileIdc, constraintSet, levelIdc) { + if (this._decoder === null || this._decoder.state === 'closed') { + this._decoder = new VideoDecoder({ + output: frame => this._handleFrame(frame), + error: e => this._handleError(e), + }); + } + const codec = 'avc1.' + + profileIdc.toString(16).padStart(2, '0') + + constraintSet.toString(16).padStart(2, '0') + + levelIdc.toString(16).padStart(2, '0'); + this._decoder.configure({ + codec: codec, + codedWidth: this._width, + codedHeight: this._height, + optimizeForLatency: true, + }); + } + + _preparePendingFrame(timestamp) { + let pending = { + timestamp: timestamp, + promise: null, + resolve: null, + frame: null, + ready: false, + keep: false, + }; + pending.promise = new Promise((resolve) => { + pending.resolve = resolve; + }); + this._pendingFrames.push(pending); + + return pending; + } + + decode(payload) { + let parser = new H264Parser(payload); + let result = null; + + // Ideally, this timestamp should come from the server, but we'll just + // approximate it instead. + let timestamp = Math.round(window.performance.now() * 1e3); + + while (true) { + let encodedFrame = parser.parse(); + if (encodedFrame === null) { + break; + } + + if (parser.profileIdc !== null) { + self._profileIdc = parser.profileIdc; + self._constraintSet = parser.constraintSet; + self._levelIdc = parser.levelIdc; + } + + if (this._decoder === null || this._decoder.state !== 'configured') { + if (!encodedFrame.key) { + Log.Warn("Missing key frame. Can't decode until one arrives"); + continue; + } + if (self._profileIdc === null) { + Log.Warn('Cannot config decoder. Have not received SPS and PPS yet.'); + continue; + } + this._configureDecoder(self._profileIdc, self._constraintSet, + self._levelIdc); + } + + result = this._preparePendingFrame(timestamp); + + const chunk = new EncodedVideoChunk({ + timestamp: timestamp, + type: encodedFrame.key ? 'key' : 'delta', + data: encodedFrame.frame, + }); + + try { + this._decoder.decode(chunk); + } catch (e) { + Log.Warn("Failed to decode:", e); + } + } + + // We only keep last frame of each payload + if (result !== null) { + result.keep = true; + } + + return result; + } +} + +export default class H264Decoder { + constructor() { + this._tick = 0; + this._contexts = {}; + } + + _contextId(x, y, width, height) { + return [x, y, width, height].join(','); + } + + _findOldestContextId() { + let oldestTick = Number.MAX_VALUE; + let oldestKey = undefined; + for (const [key, value] of Object.entries(this._contexts)) { + if (value.lastUsed < oldestTick) { + oldestTick = value.lastUsed; + oldestKey = key; + } + } + return oldestKey; + } + + _createContext(x, y, width, height) { + const maxContexts = 64; + if (Object.keys(this._contexts).length >= maxContexts) { + let oldestContextId = this._findOldestContextId(); + delete this._contexts[oldestContextId]; + } + let context = new H264Context(width, height); + this._contexts[this._contextId(x, y, width, height)] = context; + return context; + } + + _getContext(x, y, width, height) { + let context = this._contexts[this._contextId(x, y, width, height)]; + return context !== undefined ? context : this._createContext(x, y, width, height); + } + + _resetContext(x, y, width, height) { + delete this._contexts[this._contextId(x, y, width, height)]; + } + + _resetAllContexts() { + this._contexts = {}; + } + + decodeRect(x, y, width, height, sock, display, depth) { + const resetContextFlag = 1; + const resetAllContextsFlag = 2; + + if (sock.rQwait("h264 header", 8)) { + return false; + } + + const length = sock.rQshift32(); + const flags = sock.rQshift32(); + + if (sock.rQwait("h264 payload", length, 8)) { + return false; + } + + if (flags & resetAllContextsFlag) { + this._resetAllContexts(); + } else if (flags & resetContextFlag) { + this._resetContext(x, y, width, height); + } + + let context = this._getContext(x, y, width, height); + context.lastUsed = this._tick++; + + if (length !== 0) { + let payload = sock.rQshiftBytes(length, false); + let frame = context.decode(payload); + if (frame !== null) { + display.videoFrame(x, y, width, height, frame); + } + } + + return true; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/hextile.js b/web/public/cloud/vendor/novnc/core/decoders/hextile.js new file mode 100644 index 00000000..db0792bd --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/hextile.js @@ -0,0 +1,181 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import * as Log from '../util/logging.js'; + +export default class HextileDecoder { + constructor() { + this._tiles = 0; + this._lastsubencoding = 0; + this._tileBuffer = new Uint8Array(16 * 16 * 4); + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._tiles === 0) { + this._tilesX = Math.ceil(width / 16); + this._tilesY = Math.ceil(height / 16); + this._totalTiles = this._tilesX * this._tilesY; + this._tiles = this._totalTiles; + } + + while (this._tiles > 0) { + let bytes = 1; + + if (sock.rQwait("HEXTILE", bytes)) { + return false; + } + + let subencoding = sock.rQpeek8(); + if (subencoding > 30) { // Raw + throw new Error("Illegal hextile subencoding (subencoding: " + + subencoding + ")"); + } + + const currTile = this._totalTiles - this._tiles; + const tileX = currTile % this._tilesX; + const tileY = Math.floor(currTile / this._tilesX); + const tx = x + tileX * 16; + const ty = y + tileY * 16; + const tw = Math.min(16, (x + width) - tx); + const th = Math.min(16, (y + height) - ty); + + // Figure out how much we are expecting + if (subencoding & 0x01) { // Raw + bytes += tw * th * 4; + } else { + if (subencoding & 0x02) { // Background + bytes += 4; + } + if (subencoding & 0x04) { // Foreground + bytes += 4; + } + if (subencoding & 0x08) { // AnySubrects + bytes++; // Since we aren't shifting it off + + if (sock.rQwait("HEXTILE", bytes)) { + return false; + } + + let subrects = sock.rQpeekBytes(bytes).at(-1); + if (subencoding & 0x10) { // SubrectsColoured + bytes += subrects * (4 + 2); + } else { + bytes += subrects * 2; + } + } + } + + if (sock.rQwait("HEXTILE", bytes)) { + return false; + } + + // We know the encoding and have a whole tile + sock.rQshift8(); + if (subencoding === 0) { + if (this._lastsubencoding & 0x01) { + // Weird: ignore blanks are RAW + Log.Debug(" Ignoring blank after RAW"); + } else { + display.fillRect(tx, ty, tw, th, this._background); + } + } else if (subencoding & 0x01) { // Raw + let pixels = tw * th; + let data = sock.rQshiftBytes(pixels * 4, false); + // Max sure the image is fully opaque + for (let i = 0;i < pixels;i++) { + data[i * 4 + 3] = 255; + } + display.blitImage(tx, ty, tw, th, data, 0); + } else { + if (subencoding & 0x02) { // Background + this._background = new Uint8Array(sock.rQshiftBytes(4)); + } + if (subencoding & 0x04) { // Foreground + this._foreground = new Uint8Array(sock.rQshiftBytes(4)); + } + + this._startTile(tx, ty, tw, th, this._background); + if (subencoding & 0x08) { // AnySubrects + let subrects = sock.rQshift8(); + + for (let s = 0; s < subrects; s++) { + let color; + if (subencoding & 0x10) { // SubrectsColoured + color = sock.rQshiftBytes(4); + } else { + color = this._foreground; + } + const xy = sock.rQshift8(); + const sx = (xy >> 4); + const sy = (xy & 0x0f); + + const wh = sock.rQshift8(); + const sw = (wh >> 4) + 1; + const sh = (wh & 0x0f) + 1; + + this._subTile(sx, sy, sw, sh, color); + } + } + this._finishTile(display); + } + this._lastsubencoding = subencoding; + this._tiles--; + } + + return true; + } + + // start updating a tile + _startTile(x, y, width, height, color) { + this._tileX = x; + this._tileY = y; + this._tileW = width; + this._tileH = height; + + const red = color[0]; + const green = color[1]; + const blue = color[2]; + + const data = this._tileBuffer; + for (let i = 0; i < width * height * 4; i += 4) { + data[i] = red; + data[i + 1] = green; + data[i + 2] = blue; + data[i + 3] = 255; + } + } + + // update sub-rectangle of the current tile + _subTile(x, y, w, h, color) { + const red = color[0]; + const green = color[1]; + const blue = color[2]; + const xend = x + w; + const yend = y + h; + + const data = this._tileBuffer; + const width = this._tileW; + for (let j = y; j < yend; j++) { + for (let i = x; i < xend; i++) { + const p = (i + (j * width)) * 4; + data[p] = red; + data[p + 1] = green; + data[p + 2] = blue; + data[p + 3] = 255; + } + } + } + + // draw the current tile to the screen + _finishTile(display) { + display.blitImage(this._tileX, this._tileY, + this._tileW, this._tileH, + this._tileBuffer, 0); + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/jpeg.js b/web/public/cloud/vendor/novnc/core/decoders/jpeg.js new file mode 100644 index 00000000..f7984603 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/jpeg.js @@ -0,0 +1,161 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class JPEGDecoder { + constructor() { + // RealVNC will reuse the quantization tables + // and Huffman tables, so we need to cache them. + this._cachedQuantTables = []; + this._cachedHuffmanTables = []; + + this._segments = []; + } + + decodeRect(x, y, width, height, sock, display, depth) { + // A rect of JPEG encodings is simply a JPEG file + while (true) { + let segment = this._readSegment(sock); + if (segment === null) { + return false; + } + this._segments.push(segment); + // End of image? + if (segment[1] === 0xD9) { + break; + } + } + + let huffmanTables = []; + let quantTables = []; + for (let segment of this._segments) { + let type = segment[1]; + if (type === 0xC4) { + // Huffman tables + huffmanTables.push(segment); + } else if (type === 0xDB) { + // Quantization tables + quantTables.push(segment); + } + } + + const sofIndex = this._segments.findIndex( + x => x[1] == 0xC0 || x[1] == 0xC2 + ); + if (sofIndex == -1) { + throw new Error("Illegal JPEG image without SOF"); + } + + if (quantTables.length === 0) { + this._segments.splice(sofIndex+1, 0, + ...this._cachedQuantTables); + } + if (huffmanTables.length === 0) { + this._segments.splice(sofIndex+1, 0, + ...this._cachedHuffmanTables); + } + + let length = 0; + for (let segment of this._segments) { + length += segment.length; + } + + let data = new Uint8Array(length); + length = 0; + for (let segment of this._segments) { + data.set(segment, length); + length += segment.length; + } + + display.imageRect(x, y, width, height, "image/jpeg", data); + + if (huffmanTables.length !== 0) { + this._cachedHuffmanTables = huffmanTables; + } + if (quantTables.length !== 0) { + this._cachedQuantTables = quantTables; + } + + this._segments = []; + + return true; + } + + _readSegment(sock) { + if (sock.rQwait("JPEG", 2)) { + return null; + } + + let marker = sock.rQshift8(); + if (marker != 0xFF) { + throw new Error("Illegal JPEG marker received (byte: " + + marker + ")"); + } + let type = sock.rQshift8(); + if (type >= 0xD0 && type <= 0xD9 || type == 0x01) { + // No length after marker + return new Uint8Array([marker, type]); + } + + if (sock.rQwait("JPEG", 2, 2)) { + return null; + } + + let length = sock.rQshift16(); + if (length < 2) { + throw new Error("Illegal JPEG length received (length: " + + length + ")"); + } + + if (sock.rQwait("JPEG", length-2, 4)) { + return null; + } + + let extra = 0; + if (type === 0xDA) { + // start of scan + if (sock.rQwait("JPEG", length-2 + 2, 4)) { + return null; + } + + let len = sock.rQlen(); + let data = sock.rQpeekBytes(len, false); + + while (true) { + let idx = data.indexOf(0xFF, length-2+extra); + if (idx === -1) { + sock.rQwait("JPEG", Infinity, 4); + return null; + } + + if (idx === len-1) { + sock.rQwait("JPEG", Infinity, 4); + return null; + } + + if (data.at(idx+1) === 0x00 || + (data.at(idx+1) >= 0xD0 && data.at(idx+1) <= 0xD7)) { + extra = idx+2 - (length-2); + continue; + } + + extra = idx - (length-2); + break; + } + } + + let segment = new Uint8Array(2 + length + extra); + segment[0] = marker; + segment[1] = type; + segment[2] = length >> 8; + segment[3] = length; + segment.set(sock.rQshiftBytes(length-2+extra, false), 4); + + return segment; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/raw.js b/web/public/cloud/vendor/novnc/core/decoders/raw.js new file mode 100644 index 00000000..bd5d2044 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/raw.js @@ -0,0 +1,59 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class RawDecoder { + constructor() { + this._lines = 0; + } + + decodeRect(x, y, width, height, sock, display, depth) { + if ((width === 0) || (height === 0)) { + return true; + } + + if (this._lines === 0) { + this._lines = height; + } + + const pixelSize = depth == 8 ? 1 : 4; + const bytesPerLine = width * pixelSize; + + while (this._lines > 0) { + if (sock.rQwait("RAW", bytesPerLine)) { + return false; + } + + const curY = y + (height - this._lines); + + let data = sock.rQshiftBytes(bytesPerLine, false); + + // Convert data if needed + if (depth == 8) { + const newdata = new Uint8Array(width * 4); + for (let i = 0; i < width; i++) { + newdata[i * 4 + 0] = ((data[i] >> 0) & 0x3) * 255 / 3; + newdata[i * 4 + 1] = ((data[i] >> 2) & 0x3) * 255 / 3; + newdata[i * 4 + 2] = ((data[i] >> 4) & 0x3) * 255 / 3; + newdata[i * 4 + 3] = 255; + } + data = newdata; + } + + // Max sure the image is fully opaque + for (let i = 0; i < width; i++) { + data[i * 4 + 3] = 255; + } + + display.blitImage(x, curY, width, 1, data, 0); + this._lines--; + } + + return true; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/rre.js b/web/public/cloud/vendor/novnc/core/decoders/rre.js new file mode 100644 index 00000000..a5fea7c4 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/rre.js @@ -0,0 +1,44 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +export default class RREDecoder { + constructor() { + this._subrects = 0; + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._subrects === 0) { + if (sock.rQwait("RRE", 4 + 4)) { + return false; + } + + this._subrects = sock.rQshift32(); + + let color = sock.rQshiftBytes(4); // Background + display.fillRect(x, y, width, height, color); + } + + while (this._subrects > 0) { + if (sock.rQwait("RRE", 4 + 8)) { + return false; + } + + let color = sock.rQshiftBytes(4); + let sx = sock.rQshift16(); + let sy = sock.rQshift16(); + let swidth = sock.rQshift16(); + let sheight = sock.rQshift16(); + display.fillRect(x + sx, y + sy, swidth, sheight, color); + + this._subrects--; + } + + return true; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/tight.js b/web/public/cloud/vendor/novnc/core/decoders/tight.js new file mode 100644 index 00000000..1a145d4e --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/tight.js @@ -0,0 +1,393 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca) + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import * as Log from '../util/logging.js'; +import Inflator from "../inflator.js"; + +export default class TightDecoder { + constructor() { + this._ctl = null; + this._filter = null; + this._numColors = 0; + this._palette = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel) + this._len = 0; + + this._zlibs = []; + for (let i = 0; i < 4; i++) { + this._zlibs[i] = new Inflator(); + } + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._ctl === null) { + if (sock.rQwait("TIGHT compression-control", 1)) { + return false; + } + + this._ctl = sock.rQshift8(); + + // Reset streams if the server requests it + for (let i = 0; i < 4; i++) { + if ((this._ctl >> i) & 1) { + this._zlibs[i].reset(); + Log.Info("Reset zlib stream " + i); + } + } + + // Figure out filter + this._ctl = this._ctl >> 4; + } + + let ret; + + if (this._ctl === 0x08) { + ret = this._fillRect(x, y, width, height, + sock, display, depth); + } else if (this._ctl === 0x09) { + ret = this._jpegRect(x, y, width, height, + sock, display, depth); + } else if (this._ctl === 0x0A) { + ret = this._pngRect(x, y, width, height, + sock, display, depth); + } else if ((this._ctl & 0x08) == 0) { + ret = this._basicRect(this._ctl, x, y, width, height, + sock, display, depth); + } else { + throw new Error("Illegal tight compression received (ctl: " + + this._ctl + ")"); + } + + if (ret) { + this._ctl = null; + } + + return ret; + } + + _fillRect(x, y, width, height, sock, display, depth) { + if (sock.rQwait("TIGHT", 3)) { + return false; + } + + let pixel = sock.rQshiftBytes(3); + display.fillRect(x, y, width, height, pixel, false); + + return true; + } + + _jpegRect(x, y, width, height, sock, display, depth) { + let data = this._readData(sock); + if (data === null) { + return false; + } + + display.imageRect(x, y, width, height, "image/jpeg", data); + + return true; + } + + _pngRect(x, y, width, height, sock, display, depth) { + throw new Error("PNG received in standard Tight rect"); + } + + _basicRect(ctl, x, y, width, height, sock, display, depth) { + if (this._filter === null) { + if (ctl & 0x4) { + if (sock.rQwait("TIGHT", 1)) { + return false; + } + + this._filter = sock.rQshift8(); + } else { + // Implicit CopyFilter + this._filter = 0; + } + } + + let streamId = ctl & 0x3; + + let ret; + + switch (this._filter) { + case 0: // CopyFilter + ret = this._copyFilter(streamId, x, y, width, height, + sock, display, depth); + break; + case 1: // PaletteFilter + ret = this._paletteFilter(streamId, x, y, width, height, + sock, display, depth); + break; + case 2: // GradientFilter + ret = this._gradientFilter(streamId, x, y, width, height, + sock, display, depth); + break; + default: + throw new Error("Illegal tight filter received (ctl: " + + this._filter + ")"); + } + + if (ret) { + this._filter = null; + } + + return ret; + } + + _copyFilter(streamId, x, y, width, height, sock, display, depth) { + const uncompressedSize = width * height * 3; + let data; + + if (uncompressedSize === 0) { + return true; + } + + if (uncompressedSize < 12) { + if (sock.rQwait("TIGHT", uncompressedSize)) { + return false; + } + + data = sock.rQshiftBytes(uncompressedSize); + } else { + data = this._readData(sock); + if (data === null) { + return false; + } + + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); + } + + let rgbx = new Uint8Array(width * height * 4); + for (let i = 0, j = 0; i < width * height * 4; i += 4, j += 3) { + rgbx[i] = data[j]; + rgbx[i + 1] = data[j + 1]; + rgbx[i + 2] = data[j + 2]; + rgbx[i + 3] = 255; // Alpha + } + + display.blitImage(x, y, width, height, rgbx, 0, false); + + return true; + } + + _paletteFilter(streamId, x, y, width, height, sock, display, depth) { + if (this._numColors === 0) { + if (sock.rQwait("TIGHT palette", 1)) { + return false; + } + + const numColors = sock.rQpeek8() + 1; + const paletteSize = numColors * 3; + + if (sock.rQwait("TIGHT palette", 1 + paletteSize)) { + return false; + } + + this._numColors = numColors; + sock.rQskipBytes(1); + + sock.rQshiftTo(this._palette, paletteSize); + } + + const bpp = (this._numColors <= 2) ? 1 : 8; + const rowSize = Math.floor((width * bpp + 7) / 8); + const uncompressedSize = rowSize * height; + + let data; + + if (uncompressedSize === 0) { + return true; + } + + if (uncompressedSize < 12) { + if (sock.rQwait("TIGHT", uncompressedSize)) { + return false; + } + + data = sock.rQshiftBytes(uncompressedSize); + } else { + data = this._readData(sock); + if (data === null) { + return false; + } + + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); + } + + // Convert indexed (palette based) image data to RGB + if (this._numColors == 2) { + this._monoRect(x, y, width, height, data, this._palette, display); + } else { + this._paletteRect(x, y, width, height, data, this._palette, display); + } + + this._numColors = 0; + + return true; + } + + _monoRect(x, y, width, height, data, palette, display) { + // Convert indexed (palette based) image data to RGB + // TODO: reduce number of calculations inside loop + const dest = this._getScratchBuffer(width * height * 4); + const w = Math.floor((width + 7) / 8); + const w1 = Math.floor(width / 8); + + for (let y = 0; y < height; y++) { + let dp, sp, x; + for (x = 0; x < w1; x++) { + for (let b = 7; b >= 0; b--) { + dp = (y * width + x * 8 + 7 - b) * 4; + sp = (data[y * w + x] >> b & 1) * 3; + dest[dp] = palette[sp]; + dest[dp + 1] = palette[sp + 1]; + dest[dp + 2] = palette[sp + 2]; + dest[dp + 3] = 255; + } + } + + for (let b = 7; b >= 8 - width % 8; b--) { + dp = (y * width + x * 8 + 7 - b) * 4; + sp = (data[y * w + x] >> b & 1) * 3; + dest[dp] = palette[sp]; + dest[dp + 1] = palette[sp + 1]; + dest[dp + 2] = palette[sp + 2]; + dest[dp + 3] = 255; + } + } + + display.blitImage(x, y, width, height, dest, 0, false); + } + + _paletteRect(x, y, width, height, data, palette, display) { + // Convert indexed (palette based) image data to RGB + const dest = this._getScratchBuffer(width * height * 4); + const total = width * height * 4; + for (let i = 0, j = 0; i < total; i += 4, j++) { + const sp = data[j] * 3; + dest[i] = palette[sp]; + dest[i + 1] = palette[sp + 1]; + dest[i + 2] = palette[sp + 2]; + dest[i + 3] = 255; + } + + display.blitImage(x, y, width, height, dest, 0, false); + } + + _gradientFilter(streamId, x, y, width, height, sock, display, depth) { + // assume the TPIXEL is 3 bytes long + const uncompressedSize = width * height * 3; + let data; + + if (uncompressedSize === 0) { + return true; + } + + if (uncompressedSize < 12) { + if (sock.rQwait("TIGHT", uncompressedSize)) { + return false; + } + + data = sock.rQshiftBytes(uncompressedSize); + } else { + data = this._readData(sock); + if (data === null) { + return false; + } + + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); + } + + let rgbx = new Uint8Array(4 * width * height); + + let rgbxIndex = 0, dataIndex = 0; + let left = new Uint8Array(3); + for (let x = 0; x < width; x++) { + for (let c = 0; c < 3; c++) { + const prediction = left[c]; + const value = data[dataIndex++] + prediction; + rgbx[rgbxIndex++] = value; + left[c] = value; + } + rgbx[rgbxIndex++] = 255; + } + + let upperIndex = 0; + let upper = new Uint8Array(3), + upperleft = new Uint8Array(3); + for (let y = 1; y < height; y++) { + left.fill(0); + upperleft.fill(0); + for (let x = 0; x < width; x++) { + for (let c = 0; c < 3; c++) { + upper[c] = rgbx[upperIndex++]; + let prediction = left[c] + upper[c] - upperleft[c]; + if (prediction < 0) { + prediction = 0; + } else if (prediction > 255) { + prediction = 255; + } + const value = data[dataIndex++] + prediction; + rgbx[rgbxIndex++] = value; + upperleft[c] = upper[c]; + left[c] = value; + } + rgbx[rgbxIndex++] = 255; + upperIndex++; + } + } + + display.blitImage(x, y, width, height, rgbx, 0, false); + + return true; + } + + _readData(sock) { + if (this._len === 0) { + if (sock.rQwait("TIGHT", 3)) { + return null; + } + + let byte; + + byte = sock.rQshift8(); + this._len = byte & 0x7f; + if (byte & 0x80) { + byte = sock.rQshift8(); + this._len |= (byte & 0x7f) << 7; + if (byte & 0x80) { + byte = sock.rQshift8(); + this._len |= byte << 14; + } + } + } + + if (sock.rQwait("TIGHT", this._len)) { + return null; + } + + let data = sock.rQshiftBytes(this._len, false); + this._len = 0; + + return data; + } + + _getScratchBuffer(size) { + if (!this._scratchBuffer || (this._scratchBuffer.length < size)) { + this._scratchBuffer = new Uint8Array(size); + } + return this._scratchBuffer; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/tightpng.js b/web/public/cloud/vendor/novnc/core/decoders/tightpng.js new file mode 100644 index 00000000..cf1df6ba --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/tightpng.js @@ -0,0 +1,27 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import TightDecoder from './tight.js'; + +export default class TightPNGDecoder extends TightDecoder { + _pngRect(x, y, width, height, sock, display, depth) { + let data = this._readData(sock); + if (data === null) { + return false; + } + + display.imageRect(x, y, width, height, "image/png", data); + + return true; + } + + _basicRect(ctl, x, y, width, height, sock, display, depth) { + throw new Error("BasicCompression received in TightPNG rect"); + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/zlib.js b/web/public/cloud/vendor/novnc/core/decoders/zlib.js new file mode 100644 index 00000000..a876908b --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/zlib.js @@ -0,0 +1,51 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2024 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import Inflator from "../inflator.js"; + +export default class ZlibDecoder { + constructor() { + this._zlib = new Inflator(); + this._length = 0; + } + + decodeRect(x, y, width, height, sock, display, depth) { + if ((width === 0) || (height === 0)) { + return true; + } + + if (this._length === 0) { + if (sock.rQwait("ZLIB", 4)) { + return false; + } + + this._length = sock.rQshift32(); + } + + if (sock.rQwait("ZLIB", this._length)) { + return false; + } + + let data = new Uint8Array(sock.rQshiftBytes(this._length, false)); + this._length = 0; + + this._zlib.setInput(data); + data = this._zlib.inflate(width * height * 4); + this._zlib.setInput(null); + + // Max sure the image is fully opaque + for (let i = 0; i < width * height; i++) { + data[i * 4 + 3] = 255; + } + + display.blitImage(x, y, width, height, data, 0); + + return true; + } +} diff --git a/web/public/cloud/vendor/novnc/core/decoders/zrle.js b/web/public/cloud/vendor/novnc/core/decoders/zrle.js new file mode 100644 index 00000000..ef1726f6 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/decoders/zrle.js @@ -0,0 +1,185 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2021 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import Inflate from "../inflator.js"; + +const ZRLE_TILE_WIDTH = 64; +const ZRLE_TILE_HEIGHT = 64; + +export default class ZRLEDecoder { + constructor() { + this._length = 0; + this._inflator = new Inflate(); + + this._pixelBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4); + this._tileBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4); + } + + decodeRect(x, y, width, height, sock, display, depth) { + if (this._length === 0) { + if (sock.rQwait("ZLib data length", 4)) { + return false; + } + this._length = sock.rQshift32(); + } + if (sock.rQwait("Zlib data", this._length)) { + return false; + } + + const data = sock.rQshiftBytes(this._length, false); + + this._inflator.setInput(data); + + for (let ty = y; ty < y + height; ty += ZRLE_TILE_HEIGHT) { + let th = Math.min(ZRLE_TILE_HEIGHT, y + height - ty); + + for (let tx = x; tx < x + width; tx += ZRLE_TILE_WIDTH) { + let tw = Math.min(ZRLE_TILE_WIDTH, x + width - tx); + + const tileSize = tw * th; + const subencoding = this._inflator.inflate(1)[0]; + if (subencoding === 0) { + // raw data + const data = this._readPixels(tileSize); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else if (subencoding === 1) { + // solid + const background = this._readPixels(1); + display.fillRect(tx, ty, tw, th, [background[0], background[1], background[2]]); + } else if (subencoding >= 2 && subencoding <= 16) { + const data = this._decodePaletteTile(subencoding, tileSize, tw, th); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else if (subencoding === 128) { + const data = this._decodeRLETile(tileSize); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else if (subencoding >= 130 && subencoding <= 255) { + const data = this._decodeRLEPaletteTile(subencoding - 128, tileSize); + display.blitImage(tx, ty, tw, th, data, 0, false); + } else { + throw new Error('Unknown subencoding: ' + subencoding); + } + } + } + this._length = 0; + return true; + } + + _getBitsPerPixelInPalette(paletteSize) { + if (paletteSize <= 2) { + return 1; + } else if (paletteSize <= 4) { + return 2; + } else if (paletteSize <= 16) { + return 4; + } + } + + _readPixels(pixels) { + let data = this._pixelBuffer; + const buffer = this._inflator.inflate(3*pixels); + for (let i = 0, j = 0; i < pixels*4; i += 4, j += 3) { + data[i] = buffer[j]; + data[i + 1] = buffer[j + 1]; + data[i + 2] = buffer[j + 2]; + data[i + 3] = 255; // Add the Alpha + } + return data; + } + + _decodePaletteTile(paletteSize, tileSize, tilew, tileh) { + const data = this._tileBuffer; + const palette = this._readPixels(paletteSize); + const bitsPerPixel = this._getBitsPerPixelInPalette(paletteSize); + const mask = (1 << bitsPerPixel) - 1; + + let offset = 0; + let encoded = this._inflator.inflate(1)[0]; + + for (let y=0; y>shift) & mask; + + data[offset] = palette[indexInPalette * 4]; + data[offset + 1] = palette[indexInPalette * 4 + 1]; + data[offset + 2] = palette[indexInPalette * 4 + 2]; + data[offset + 3] = palette[indexInPalette * 4 + 3]; + offset += 4; + shift-=bitsPerPixel; + } + if (shift<8-bitsPerPixel && y= 128) { + indexInPalette -= 128; + length = this._readRLELength(); + } + if (indexInPalette > paletteSize) { + throw new Error('Too big index in palette: ' + indexInPalette + ', palette size: ' + paletteSize); + } + if (offset + length > tileSize) { + throw new Error('Too big rle length in palette mode: ' + length + ', allowed length is: ' + (tileSize - offset)); + } + + for (let j = 0; j < length; j++) { + data[offset * 4] = palette[indexInPalette * 4]; + data[offset * 4 + 1] = palette[indexInPalette * 4 + 1]; + data[offset * 4 + 2] = palette[indexInPalette * 4 + 2]; + data[offset * 4 + 3] = palette[indexInPalette * 4 + 3]; + offset++; + } + } + return data; + } + + _readRLELength() { + let length = 0; + let current = 0; + do { + current = this._inflator.inflate(1)[0]; + length += current; + } while (current === 255); + return length + 1; + } +} diff --git a/web/public/cloud/vendor/novnc/core/deflator.js b/web/public/cloud/vendor/novnc/core/deflator.js new file mode 100644 index 00000000..af24009e --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/deflator.js @@ -0,0 +1,84 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +import { deflateInit, deflate } from "../vendor/pako/lib/zlib/deflate.js"; +import { Z_FULL_FLUSH, Z_DEFAULT_COMPRESSION } from "../vendor/pako/lib/zlib/deflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; + +export default class Deflator { + constructor() { + this.strm = new ZStream(); + this.chunkSize = 1024 * 10 * 10; + this.outputBuffer = new Uint8Array(this.chunkSize); + + deflateInit(this.strm, Z_DEFAULT_COMPRESSION); + } + + deflate(inData) { + /* eslint-disable camelcase */ + this.strm.input = inData; + this.strm.avail_in = this.strm.input.length; + this.strm.next_in = 0; + this.strm.output = this.outputBuffer; + this.strm.avail_out = this.chunkSize; + this.strm.next_out = 0; + /* eslint-enable camelcase */ + + let lastRet = deflate(this.strm, Z_FULL_FLUSH); + let outData = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + + if (lastRet < 0) { + throw new Error("zlib deflate failed"); + } + + if (this.strm.avail_in > 0) { + // Read chunks until done + + let chunks = [outData]; + let totalLen = outData.length; + do { + /* eslint-disable camelcase */ + this.strm.output = new Uint8Array(this.chunkSize); + this.strm.next_out = 0; + this.strm.avail_out = this.chunkSize; + /* eslint-enable camelcase */ + + lastRet = deflate(this.strm, Z_FULL_FLUSH); + + if (lastRet < 0) { + throw new Error("zlib deflate failed"); + } + + let chunk = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + totalLen += chunk.length; + chunks.push(chunk); + } while (this.strm.avail_in > 0); + + // Combine chunks into a single data + + let newData = new Uint8Array(totalLen); + let offset = 0; + + for (let i = 0; i < chunks.length; i++) { + newData.set(chunks[i], offset); + offset += chunks[i].length; + } + + outData = newData; + } + + /* eslint-disable camelcase */ + this.strm.input = null; + this.strm.avail_in = 0; + this.strm.next_in = 0; + /* eslint-enable camelcase */ + + return outData; + } + +} diff --git a/web/public/cloud/vendor/novnc/core/display.js b/web/public/cloud/vendor/novnc/core/display.js new file mode 100644 index 00000000..4efd6f4b --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/display.js @@ -0,0 +1,578 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +import * as Log from './util/logging.js'; +import Base64 from "./base64.js"; +import { toSigned32bit } from './util/int.js'; + +export default class Display { + constructor(target) { + this._drawCtx = null; + + this._renderQ = []; // queue drawing actions for in-oder rendering + this._flushPromise = null; + + // the full frame buffer (logical canvas) size + this._fbWidth = 0; + this._fbHeight = 0; + + this._prevDrawStyle = ""; + + Log.Debug(">> Display.constructor"); + + // The visible canvas + this._target = target; + + if (!this._target) { + throw new Error("Target must be set"); + } + + if (typeof this._target === 'string') { + throw new Error('target must be a DOM element'); + } + + if (!this._target.getContext) { + throw new Error("no getContext method"); + } + + this._targetCtx = this._target.getContext('2d'); + + // the visible canvas viewport (i.e. what actually gets seen) + this._viewportLoc = { 'x': 0, 'y': 0, 'w': this._target.width, 'h': this._target.height }; + + // The hidden canvas, where we do the actual rendering + this._backbuffer = document.createElement('canvas'); + this._drawCtx = this._backbuffer.getContext('2d'); + + this._damageBounds = { left: 0, top: 0, + right: this._backbuffer.width, + bottom: this._backbuffer.height }; + + Log.Debug("User Agent: " + navigator.userAgent); + + Log.Debug("<< Display.constructor"); + + // ===== PROPERTIES ===== + + this._scale = 1.0; + this._clipViewport = false; + } + + // ===== PROPERTIES ===== + + get scale() { return this._scale; } + set scale(scale) { + this._rescale(scale); + } + + get clipViewport() { return this._clipViewport; } + set clipViewport(viewport) { + this._clipViewport = viewport; + // May need to readjust the viewport dimensions + const vp = this._viewportLoc; + this.viewportChangeSize(vp.w, vp.h); + this.viewportChangePos(0, 0); + } + + get width() { + return this._fbWidth; + } + + get height() { + return this._fbHeight; + } + + // ===== PUBLIC METHODS ===== + + viewportChangePos(deltaX, deltaY) { + const vp = this._viewportLoc; + deltaX = Math.floor(deltaX); + deltaY = Math.floor(deltaY); + + if (!this._clipViewport) { + deltaX = -vp.w; // clamped later of out of bounds + deltaY = -vp.h; + } + + const vx2 = vp.x + vp.w - 1; + const vy2 = vp.y + vp.h - 1; + + // Position change + + if (deltaX < 0 && vp.x + deltaX < 0) { + deltaX = -vp.x; + } + if (vx2 + deltaX >= this._fbWidth) { + deltaX -= vx2 + deltaX - this._fbWidth + 1; + } + + if (vp.y + deltaY < 0) { + deltaY = -vp.y; + } + if (vy2 + deltaY >= this._fbHeight) { + deltaY -= (vy2 + deltaY - this._fbHeight + 1); + } + + if (deltaX === 0 && deltaY === 0) { + return; + } + Log.Debug("viewportChange deltaX: " + deltaX + ", deltaY: " + deltaY); + + vp.x += deltaX; + vp.y += deltaY; + + this._damage(vp.x, vp.y, vp.w, vp.h); + + this.flip(); + } + + viewportChangeSize(width, height) { + + if (!this._clipViewport || + typeof(width) === "undefined" || + typeof(height) === "undefined") { + + Log.Debug("Setting viewport to full display region"); + width = this._fbWidth; + height = this._fbHeight; + } + + width = Math.floor(width); + height = Math.floor(height); + + if (width > this._fbWidth) { + width = this._fbWidth; + } + if (height > this._fbHeight) { + height = this._fbHeight; + } + + const vp = this._viewportLoc; + if (vp.w !== width || vp.h !== height) { + vp.w = width; + vp.h = height; + + const canvas = this._target; + canvas.width = width; + canvas.height = height; + + // The position might need to be updated if we've grown + this.viewportChangePos(0, 0); + + this._damage(vp.x, vp.y, vp.w, vp.h); + this.flip(); + + // Update the visible size of the target canvas + this._rescale(this._scale); + } + } + + absX(x) { + if (this._scale === 0) { + return 0; + } + return toSigned32bit(x / this._scale + this._viewportLoc.x); + } + + absY(y) { + if (this._scale === 0) { + return 0; + } + return toSigned32bit(y / this._scale + this._viewportLoc.y); + } + + resize(width, height) { + this._prevDrawStyle = ""; + + this._fbWidth = width; + this._fbHeight = height; + + const canvas = this._backbuffer; + if (canvas.width !== width || canvas.height !== height) { + + // We have to save the canvas data since changing the size will clear it + let saveImg = null; + if (canvas.width > 0 && canvas.height > 0) { + saveImg = this._drawCtx.getImageData(0, 0, canvas.width, canvas.height); + } + + if (canvas.width !== width) { + canvas.width = width; + } + if (canvas.height !== height) { + canvas.height = height; + } + + if (saveImg) { + this._drawCtx.putImageData(saveImg, 0, 0); + } + } + + // Readjust the viewport as it may be incorrectly sized + // and positioned + const vp = this._viewportLoc; + this.viewportChangeSize(vp.w, vp.h); + this.viewportChangePos(0, 0); + } + + getImageData() { + return this._drawCtx.getImageData(0, 0, this.width, this.height); + } + + toDataURL(type, encoderOptions) { + return this._backbuffer.toDataURL(type, encoderOptions); + } + + toBlob(callback, type, quality) { + return this._backbuffer.toBlob(callback, type, quality); + } + + // Track what parts of the visible canvas that need updating + _damage(x, y, w, h) { + if (x < this._damageBounds.left) { + this._damageBounds.left = x; + } + if (y < this._damageBounds.top) { + this._damageBounds.top = y; + } + if ((x + w) > this._damageBounds.right) { + this._damageBounds.right = x + w; + } + if ((y + h) > this._damageBounds.bottom) { + this._damageBounds.bottom = y + h; + } + } + + // Update the visible canvas with the contents of the + // rendering canvas + flip(fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ + 'type': 'flip' + }); + } else { + let x = this._damageBounds.left; + let y = this._damageBounds.top; + let w = this._damageBounds.right - x; + let h = this._damageBounds.bottom - y; + + let vx = x - this._viewportLoc.x; + let vy = y - this._viewportLoc.y; + + if (vx < 0) { + w += vx; + x -= vx; + vx = 0; + } + if (vy < 0) { + h += vy; + y -= vy; + vy = 0; + } + + if ((vx + w) > this._viewportLoc.w) { + w = this._viewportLoc.w - vx; + } + if ((vy + h) > this._viewportLoc.h) { + h = this._viewportLoc.h - vy; + } + + if ((w > 0) && (h > 0)) { + // FIXME: We may need to disable image smoothing here + // as well (see copyImage()), but we haven't + // noticed any problem yet. + this._targetCtx.drawImage(this._backbuffer, + x, y, w, h, + vx, vy, w, h); + } + + this._damageBounds.left = this._damageBounds.top = 65535; + this._damageBounds.right = this._damageBounds.bottom = 0; + } + } + + pending() { + return this._renderQ.length > 0; + } + + flush() { + if (this._renderQ.length === 0) { + return Promise.resolve(); + } else { + if (this._flushPromise === null) { + this._flushPromise = new Promise((resolve) => { + this._flushResolve = resolve; + }); + } + return this._flushPromise; + } + } + + fillRect(x, y, width, height, color, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ + 'type': 'fill', + 'x': x, + 'y': y, + 'width': width, + 'height': height, + 'color': color + }); + } else { + this._setFillColor(color); + this._drawCtx.fillRect(x, y, width, height); + this._damage(x, y, width, height); + } + } + + copyImage(oldX, oldY, newX, newY, w, h, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ + 'type': 'copy', + 'oldX': oldX, + 'oldY': oldY, + 'x': newX, + 'y': newY, + 'width': w, + 'height': h, + }); + } else { + // Due to this bug among others [1] we need to disable the image-smoothing to + // avoid getting a blur effect when copying data. + // + // 1. https://bugzilla.mozilla.org/show_bug.cgi?id=1194719 + // + // We need to set these every time since all properties are reset + // when the the size is changed + this._drawCtx.mozImageSmoothingEnabled = false; + this._drawCtx.webkitImageSmoothingEnabled = false; + this._drawCtx.msImageSmoothingEnabled = false; + this._drawCtx.imageSmoothingEnabled = false; + + this._drawCtx.drawImage(this._backbuffer, + oldX, oldY, w, h, + newX, newY, w, h); + this._damage(newX, newY, w, h); + } + } + + imageRect(x, y, width, height, mime, arr) { + /* The internal logic cannot handle empty images, so bail early */ + if ((width === 0) || (height === 0)) { + return; + } + + const img = new Image(); + img.src = "data: " + mime + ";base64," + Base64.encode(arr); + + this._renderQPush({ + 'type': 'img', + 'img': img, + 'x': x, + 'y': y, + 'width': width, + 'height': height + }); + } + + videoFrame(x, y, width, height, frame) { + this._renderQPush({ + 'type': 'frame', + 'frame': frame, + 'x': x, + 'y': y, + 'width': width, + 'height': height + }); + } + + blitImage(x, y, width, height, arr, offset, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + // NB(directxman12): it's technically more performant here to use preallocated arrays, + // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, + // this probably isn't getting called *nearly* as much + const newArr = new Uint8Array(width * height * 4); + newArr.set(new Uint8Array(arr.buffer, 0, newArr.length)); + this._renderQPush({ + 'type': 'blit', + 'data': newArr, + 'x': x, + 'y': y, + 'width': width, + 'height': height, + }); + } else { + // NB(directxman12): arr must be an Type Array view + let data = new Uint8ClampedArray(arr.buffer, + arr.byteOffset + offset, + width * height * 4); + let img = new ImageData(data, width, height); + this._drawCtx.putImageData(img, x, y); + this._damage(x, y, width, height); + } + } + + drawImage(img, ...args) { + this._drawCtx.drawImage(img, ...args); + + if (args.length <= 4) { + const [x, y] = args; + this._damage(x, y, img.width, img.height); + } else { + const [,, sw, sh, dx, dy] = args; + this._damage(dx, dy, sw, sh); + } + } + + autoscale(containerWidth, containerHeight) { + let scaleRatio; + + if (containerWidth === 0 || containerHeight === 0) { + scaleRatio = 0; + + } else { + + const vp = this._viewportLoc; + const targetAspectRatio = containerWidth / containerHeight; + const fbAspectRatio = vp.w / vp.h; + + if (fbAspectRatio >= targetAspectRatio) { + scaleRatio = containerWidth / vp.w; + } else { + scaleRatio = containerHeight / vp.h; + } + } + + this._rescale(scaleRatio); + } + + // ===== PRIVATE METHODS ===== + + _rescale(factor) { + this._scale = factor; + const vp = this._viewportLoc; + + // NB(directxman12): If you set the width directly, or set the + // style width to a number, the canvas is cleared. + // However, if you set the style width to a string + // ('NNNpx'), the canvas is scaled without clearing. + const width = factor * vp.w + 'px'; + const height = factor * vp.h + 'px'; + + if ((this._target.style.width !== width) || + (this._target.style.height !== height)) { + this._target.style.width = width; + this._target.style.height = height; + } + } + + _setFillColor(color) { + const newStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')'; + if (newStyle !== this._prevDrawStyle) { + this._drawCtx.fillStyle = newStyle; + this._prevDrawStyle = newStyle; + } + } + + _renderQPush(action) { + this._renderQ.push(action); + if (this._renderQ.length === 1) { + // If this can be rendered immediately it will be, otherwise + // the scanner will wait for the relevant event + this._scanRenderQ(); + } + } + + _resumeRenderQ() { + // "this" is the object that is ready, not the + // display object + this.removeEventListener('load', this._noVNCDisplay._resumeRenderQ); + this._noVNCDisplay._scanRenderQ(); + } + + _scanRenderQ() { + let ready = true; + while (ready && this._renderQ.length > 0) { + const a = this._renderQ[0]; + switch (a.type) { + case 'flip': + this.flip(true); + break; + case 'copy': + this.copyImage(a.oldX, a.oldY, a.x, a.y, a.width, a.height, true); + break; + case 'fill': + this.fillRect(a.x, a.y, a.width, a.height, a.color, true); + break; + case 'blit': + this.blitImage(a.x, a.y, a.width, a.height, a.data, 0, true); + break; + case 'img': + if (a.img.complete) { + if (a.img.width !== a.width || a.img.height !== a.height) { + Log.Error("Decoded image has incorrect dimensions. Got " + + a.img.width + "x" + a.img.height + ". Expected " + + a.width + "x" + a.height + "."); + return; + } + this.drawImage(a.img, a.x, a.y); + // This helps the browser free the memory right + // away, rather than ballooning + a.img.src = ""; + } else { + a.img._noVNCDisplay = this; + a.img.addEventListener('load', this._resumeRenderQ); + // We need to wait for this image to 'load' + // to keep things in-order + ready = false; + } + break; + case 'frame': + if (a.frame.ready) { + // The encoded frame may be larger than the rect due to + // limitations of the encoder, so we need to crop the + // frame. + let frame = a.frame.frame; + if (frame.codedWidth < a.width || frame.codedHeight < a.height) { + Log.Warn("Decoded video frame does not cover its full rectangle area. Expecting at least " + + a.width + "x" + a.height + " but got " + + frame.codedWidth + "x" + frame.codedHeight); + } + const sx = 0; + const sy = 0; + const sw = a.width; + const sh = a.height; + const dx = a.x; + const dy = a.y; + const dw = sw; + const dh = sh; + this.drawImage(frame, sx, sy, sw, sh, dx, dy, dw, dh); + frame.close(); + } else { + let display = this; + a.frame.promise.then(() => { + display._scanRenderQ(); + }); + ready = false; + } + break; + } + + if (ready) { + this._renderQ.shift(); + } + } + + if (this._renderQ.length === 0 && + this._flushPromise !== null) { + this._flushResolve(); + this._flushPromise = null; + this._flushResolve = null; + } + } +} diff --git a/web/public/cloud/vendor/novnc/core/encodings.js b/web/public/cloud/vendor/novnc/core/encodings.js new file mode 100644 index 00000000..7afcb17f --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/encodings.js @@ -0,0 +1,54 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +export const encodings = { + encodingRaw: 0, + encodingCopyRect: 1, + encodingRRE: 2, + encodingHextile: 5, + encodingZlib: 6, + encodingTight: 7, + encodingZRLE: 16, + encodingTightPNG: -260, + encodingJPEG: 21, + encodingH264: 50, + + pseudoEncodingQualityLevel9: -23, + pseudoEncodingQualityLevel0: -32, + pseudoEncodingDesktopSize: -223, + pseudoEncodingLastRect: -224, + pseudoEncodingCursor: -239, + pseudoEncodingQEMUExtendedKeyEvent: -258, + pseudoEncodingQEMULedEvent: -261, + pseudoEncodingDesktopName: -307, + pseudoEncodingExtendedDesktopSize: -308, + pseudoEncodingXvp: -309, + pseudoEncodingFence: -312, + pseudoEncodingContinuousUpdates: -313, + pseudoEncodingExtendedMouseButtons: -316, + pseudoEncodingCompressLevel9: -247, + pseudoEncodingCompressLevel0: -256, + pseudoEncodingVMwareCursor: 0x574d5664, + pseudoEncodingExtendedClipboard: 0xc0a1e5ce +}; + +export function encodingName(num) { + switch (num) { + case encodings.encodingRaw: return "Raw"; + case encodings.encodingCopyRect: return "CopyRect"; + case encodings.encodingRRE: return "RRE"; + case encodings.encodingHextile: return "Hextile"; + case encodings.encodingZlib: return "Zlib"; + case encodings.encodingTight: return "Tight"; + case encodings.encodingZRLE: return "ZRLE"; + case encodings.encodingTightPNG: return "TightPNG"; + case encodings.encodingJPEG: return "JPEG"; + case encodings.encodingH264: return "H.264"; + default: return "[unknown encoding " + num + "]"; + } +} diff --git a/web/public/cloud/vendor/novnc/core/inflator.js b/web/public/cloud/vendor/novnc/core/inflator.js new file mode 100644 index 00000000..7ef47f13 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/inflator.js @@ -0,0 +1,65 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +import { inflateInit, inflate, inflateReset } from "../vendor/pako/lib/zlib/inflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; + +export default class Inflate { + constructor() { + this.strm = new ZStream(); + this.chunkSize = 1024 * 10 * 10; + this.strm.output = new Uint8Array(this.chunkSize); + + inflateInit(this.strm); + } + + setInput(data) { + if (!data) { + //FIXME: flush remaining data. + /* eslint-disable camelcase */ + this.strm.input = null; + this.strm.avail_in = 0; + this.strm.next_in = 0; + } else { + this.strm.input = data; + this.strm.avail_in = this.strm.input.length; + this.strm.next_in = 0; + /* eslint-enable camelcase */ + } + } + + inflate(expected) { + // resize our output buffer if it's too small + // (we could just use multiple chunks, but that would cause an extra + // allocation each time to flatten the chunks) + if (expected > this.chunkSize) { + this.chunkSize = expected; + this.strm.output = new Uint8Array(this.chunkSize); + } + + /* eslint-disable camelcase */ + this.strm.next_out = 0; + this.strm.avail_out = expected; + /* eslint-enable camelcase */ + + let ret = inflate(this.strm, 0); // Flush argument not used. + if (ret < 0) { + throw new Error("zlib inflate failed"); + } + + if (this.strm.next_out != expected) { + throw new Error("Incomplete zlib block"); + } + + return new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + } + + reset() { + inflateReset(this.strm); + } +} diff --git a/web/public/cloud/vendor/novnc/core/input/domkeytable.js b/web/public/cloud/vendor/novnc/core/input/domkeytable.js new file mode 100644 index 00000000..9e599f74 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/domkeytable.js @@ -0,0 +1,311 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +import KeyTable from "./keysym.js"; + +/* + * Mapping between HTML key values and VNC/X11 keysyms for "special" + * keys that cannot be handled via their Unicode codepoint. + * + * See https://www.w3.org/TR/uievents-key/ for possible values. + */ + +const DOMKeyTable = {}; + +function addStandard(key, standard) { + if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); + DOMKeyTable[key] = [standard, standard, standard, standard]; +} + +function addLeftRight(key, left, right) { + if (left === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (right === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); + DOMKeyTable[key] = [left, left, right, left]; +} + +function addNumpad(key, standard, numpad) { + if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (numpad === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); + if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); + DOMKeyTable[key] = [standard, standard, standard, numpad]; +} + +// 3.2. Modifier Keys + +addLeftRight("Alt", KeyTable.XK_Alt_L, KeyTable.XK_Alt_R); +addStandard("AltGraph", KeyTable.XK_ISO_Level3_Shift); +addStandard("CapsLock", KeyTable.XK_Caps_Lock); +addLeftRight("Control", KeyTable.XK_Control_L, KeyTable.XK_Control_R); +// - Fn +// - FnLock +addLeftRight("Meta", KeyTable.XK_Super_L, KeyTable.XK_Super_R); +addStandard("NumLock", KeyTable.XK_Num_Lock); +addStandard("ScrollLock", KeyTable.XK_Scroll_Lock); +addLeftRight("Shift", KeyTable.XK_Shift_L, KeyTable.XK_Shift_R); +// - Symbol +// - SymbolLock +// - Hyper +// - Super + +// 3.3. Whitespace Keys + +addNumpad("Enter", KeyTable.XK_Return, KeyTable.XK_KP_Enter); +addStandard("Tab", KeyTable.XK_Tab); +addNumpad(" ", KeyTable.XK_space, KeyTable.XK_KP_Space); + +// 3.4. Navigation Keys + +addNumpad("ArrowDown", KeyTable.XK_Down, KeyTable.XK_KP_Down); +addNumpad("ArrowLeft", KeyTable.XK_Left, KeyTable.XK_KP_Left); +addNumpad("ArrowRight", KeyTable.XK_Right, KeyTable.XK_KP_Right); +addNumpad("ArrowUp", KeyTable.XK_Up, KeyTable.XK_KP_Up); +addNumpad("End", KeyTable.XK_End, KeyTable.XK_KP_End); +addNumpad("Home", KeyTable.XK_Home, KeyTable.XK_KP_Home); +addNumpad("PageDown", KeyTable.XK_Next, KeyTable.XK_KP_Next); +addNumpad("PageUp", KeyTable.XK_Prior, KeyTable.XK_KP_Prior); + +// 3.5. Editing Keys + +addStandard("Backspace", KeyTable.XK_BackSpace); +// Browsers send "Clear" for the numpad 5 without NumLock because +// Windows uses VK_Clear for that key. But Unix expects KP_Begin for +// that scenario. +addNumpad("Clear", KeyTable.XK_Clear, KeyTable.XK_KP_Begin); +addStandard("Copy", KeyTable.XF86XK_Copy); +// - CrSel +addStandard("Cut", KeyTable.XF86XK_Cut); +addNumpad("Delete", KeyTable.XK_Delete, KeyTable.XK_KP_Delete); +// - EraseEof +// - ExSel +addNumpad("Insert", KeyTable.XK_Insert, KeyTable.XK_KP_Insert); +addStandard("Paste", KeyTable.XF86XK_Paste); +addStandard("Redo", KeyTable.XK_Redo); +addStandard("Undo", KeyTable.XK_Undo); + +// 3.6. UI Keys + +// - Accept +// - Again (could just be XK_Redo) +// - Attn +addStandard("Cancel", KeyTable.XK_Cancel); +addStandard("ContextMenu", KeyTable.XK_Menu); +addStandard("Escape", KeyTable.XK_Escape); +addStandard("Execute", KeyTable.XK_Execute); +addStandard("Find", KeyTable.XK_Find); +addStandard("Help", KeyTable.XK_Help); +addStandard("Pause", KeyTable.XK_Pause); +// - Play +// - Props +addStandard("Select", KeyTable.XK_Select); +addStandard("ZoomIn", KeyTable.XF86XK_ZoomIn); +addStandard("ZoomOut", KeyTable.XF86XK_ZoomOut); + +// 3.7. Device Keys + +addStandard("BrightnessDown", KeyTable.XF86XK_MonBrightnessDown); +addStandard("BrightnessUp", KeyTable.XF86XK_MonBrightnessUp); +addStandard("Eject", KeyTable.XF86XK_Eject); +addStandard("LogOff", KeyTable.XF86XK_LogOff); +addStandard("Power", KeyTable.XF86XK_PowerOff); +addStandard("PowerOff", KeyTable.XF86XK_PowerDown); +addStandard("PrintScreen", KeyTable.XK_Print); +addStandard("Hibernate", KeyTable.XF86XK_Hibernate); +addStandard("Standby", KeyTable.XF86XK_Standby); +addStandard("WakeUp", KeyTable.XF86XK_WakeUp); + +// 3.8. IME and Composition Keys + +addStandard("AllCandidates", KeyTable.XK_MultipleCandidate); +addStandard("Alphanumeric", KeyTable.XK_Eisu_toggle); +addStandard("CodeInput", KeyTable.XK_Codeinput); +addStandard("Compose", KeyTable.XK_Multi_key); +addStandard("Convert", KeyTable.XK_Henkan); +// - Dead +// - FinalMode +addStandard("GroupFirst", KeyTable.XK_ISO_First_Group); +addStandard("GroupLast", KeyTable.XK_ISO_Last_Group); +addStandard("GroupNext", KeyTable.XK_ISO_Next_Group); +addStandard("GroupPrevious", KeyTable.XK_ISO_Prev_Group); +// - ModeChange (XK_Mode_switch is often used for AltGr) +// - NextCandidate +addStandard("NonConvert", KeyTable.XK_Muhenkan); +addStandard("PreviousCandidate", KeyTable.XK_PreviousCandidate); +// - Process +addStandard("SingleCandidate", KeyTable.XK_SingleCandidate); +addStandard("HangulMode", KeyTable.XK_Hangul); +addStandard("HanjaMode", KeyTable.XK_Hangul_Hanja); +addStandard("JunjaMode", KeyTable.XK_Hangul_Jeonja); +addStandard("Eisu", KeyTable.XK_Eisu_toggle); +addStandard("Hankaku", KeyTable.XK_Hankaku); +addStandard("Hiragana", KeyTable.XK_Hiragana); +addStandard("HiraganaKatakana", KeyTable.XK_Hiragana_Katakana); +addStandard("KanaMode", KeyTable.XK_Kana_Shift); // could also be _Kana_Lock +addStandard("KanjiMode", KeyTable.XK_Kanji); +addStandard("Katakana", KeyTable.XK_Katakana); +addStandard("Romaji", KeyTable.XK_Romaji); +addStandard("Zenkaku", KeyTable.XK_Zenkaku); +addStandard("ZenkakuHankaku", KeyTable.XK_Zenkaku_Hankaku); + +// 3.9. General-Purpose Function Keys + +addStandard("F1", KeyTable.XK_F1); +addStandard("F2", KeyTable.XK_F2); +addStandard("F3", KeyTable.XK_F3); +addStandard("F4", KeyTable.XK_F4); +addStandard("F5", KeyTable.XK_F5); +addStandard("F6", KeyTable.XK_F6); +addStandard("F7", KeyTable.XK_F7); +addStandard("F8", KeyTable.XK_F8); +addStandard("F9", KeyTable.XK_F9); +addStandard("F10", KeyTable.XK_F10); +addStandard("F11", KeyTable.XK_F11); +addStandard("F12", KeyTable.XK_F12); +addStandard("F13", KeyTable.XK_F13); +addStandard("F14", KeyTable.XK_F14); +addStandard("F15", KeyTable.XK_F15); +addStandard("F16", KeyTable.XK_F16); +addStandard("F17", KeyTable.XK_F17); +addStandard("F18", KeyTable.XK_F18); +addStandard("F19", KeyTable.XK_F19); +addStandard("F20", KeyTable.XK_F20); +addStandard("F21", KeyTable.XK_F21); +addStandard("F22", KeyTable.XK_F22); +addStandard("F23", KeyTable.XK_F23); +addStandard("F24", KeyTable.XK_F24); +addStandard("F25", KeyTable.XK_F25); +addStandard("F26", KeyTable.XK_F26); +addStandard("F27", KeyTable.XK_F27); +addStandard("F28", KeyTable.XK_F28); +addStandard("F29", KeyTable.XK_F29); +addStandard("F30", KeyTable.XK_F30); +addStandard("F31", KeyTable.XK_F31); +addStandard("F32", KeyTable.XK_F32); +addStandard("F33", KeyTable.XK_F33); +addStandard("F34", KeyTable.XK_F34); +addStandard("F35", KeyTable.XK_F35); +// - Soft1... + +// 3.10. Multimedia Keys + +// - ChannelDown +// - ChannelUp +addStandard("Close", KeyTable.XF86XK_Close); +addStandard("MailForward", KeyTable.XF86XK_MailForward); +addStandard("MailReply", KeyTable.XF86XK_Reply); +addStandard("MailSend", KeyTable.XF86XK_Send); +// - MediaClose +addStandard("MediaFastForward", KeyTable.XF86XK_AudioForward); +addStandard("MediaPause", KeyTable.XF86XK_AudioPause); +addStandard("MediaPlay", KeyTable.XF86XK_AudioPlay); +// - MediaPlayPause +addStandard("MediaRecord", KeyTable.XF86XK_AudioRecord); +addStandard("MediaRewind", KeyTable.XF86XK_AudioRewind); +addStandard("MediaStop", KeyTable.XF86XK_AudioStop); +addStandard("MediaTrackNext", KeyTable.XF86XK_AudioNext); +addStandard("MediaTrackPrevious", KeyTable.XF86XK_AudioPrev); +addStandard("New", KeyTable.XF86XK_New); +addStandard("Open", KeyTable.XF86XK_Open); +addStandard("Print", KeyTable.XK_Print); +addStandard("Save", KeyTable.XF86XK_Save); +addStandard("SpellCheck", KeyTable.XF86XK_Spell); + +// 3.11. Multimedia Numpad Keys + +// - Key11 +// - Key12 + +// 3.12. Audio Keys + +// - AudioBalanceLeft +// - AudioBalanceRight +// - AudioBassBoostDown +// - AudioBassBoostToggle +// - AudioBassBoostUp +// - AudioFaderFront +// - AudioFaderRear +// - AudioSurroundModeNext +// - AudioTrebleDown +// - AudioTrebleUp +addStandard("AudioVolumeDown", KeyTable.XF86XK_AudioLowerVolume); +addStandard("AudioVolumeUp", KeyTable.XF86XK_AudioRaiseVolume); +addStandard("AudioVolumeMute", KeyTable.XF86XK_AudioMute); +// - MicrophoneToggle +// - MicrophoneVolumeDown +// - MicrophoneVolumeUp +addStandard("MicrophoneVolumeMute", KeyTable.XF86XK_AudioMicMute); + +// 3.13. Speech Keys + +// - SpeechCorrectionList +// - SpeechInputToggle + +// 3.14. Application Keys + +addStandard("LaunchApplication1", KeyTable.XF86XK_MyComputer); +addStandard("LaunchApplication2", KeyTable.XF86XK_Calculator); +addStandard("LaunchCalendar", KeyTable.XF86XK_Calendar); +// - LaunchContacts +addStandard("LaunchMail", KeyTable.XF86XK_Mail); +addStandard("LaunchMediaPlayer", KeyTable.XF86XK_AudioMedia); +addStandard("LaunchMusicPlayer", KeyTable.XF86XK_Music); +addStandard("LaunchPhone", KeyTable.XF86XK_Phone); +addStandard("LaunchScreenSaver", KeyTable.XF86XK_ScreenSaver); +addStandard("LaunchSpreadsheet", KeyTable.XF86XK_Excel); +addStandard("LaunchWebBrowser", KeyTable.XF86XK_WWW); +addStandard("LaunchWebCam", KeyTable.XF86XK_WebCam); +addStandard("LaunchWordProcessor", KeyTable.XF86XK_Word); + +// 3.15. Browser Keys + +addStandard("BrowserBack", KeyTable.XF86XK_Back); +addStandard("BrowserFavorites", KeyTable.XF86XK_Favorites); +addStandard("BrowserForward", KeyTable.XF86XK_Forward); +addStandard("BrowserHome", KeyTable.XF86XK_HomePage); +addStandard("BrowserRefresh", KeyTable.XF86XK_Refresh); +addStandard("BrowserSearch", KeyTable.XF86XK_Search); +addStandard("BrowserStop", KeyTable.XF86XK_Stop); + +// 3.16. Mobile Phone Keys + +// - A whole bunch... + +// 3.17. TV Keys + +// - A whole bunch... + +// 3.18. Media Controller Keys + +// - A whole bunch... +addStandard("Dimmer", KeyTable.XF86XK_BrightnessAdjust); +addStandard("MediaAudioTrack", KeyTable.XF86XK_AudioCycleTrack); +addStandard("RandomToggle", KeyTable.XF86XK_AudioRandomPlay); +addStandard("SplitScreenToggle", KeyTable.XF86XK_SplitScreen); +addStandard("Subtitle", KeyTable.XF86XK_Subtitle); +addStandard("VideoModeNext", KeyTable.XF86XK_Next_VMode); + +// Extra: Numpad + +addNumpad("=", KeyTable.XK_equal, KeyTable.XK_KP_Equal); +addNumpad("+", KeyTable.XK_plus, KeyTable.XK_KP_Add); +addNumpad("-", KeyTable.XK_minus, KeyTable.XK_KP_Subtract); +addNumpad("*", KeyTable.XK_asterisk, KeyTable.XK_KP_Multiply); +addNumpad("/", KeyTable.XK_slash, KeyTable.XK_KP_Divide); +addNumpad(".", KeyTable.XK_period, KeyTable.XK_KP_Decimal); +addNumpad(",", KeyTable.XK_comma, KeyTable.XK_KP_Separator); +addNumpad("0", KeyTable.XK_0, KeyTable.XK_KP_0); +addNumpad("1", KeyTable.XK_1, KeyTable.XK_KP_1); +addNumpad("2", KeyTable.XK_2, KeyTable.XK_KP_2); +addNumpad("3", KeyTable.XK_3, KeyTable.XK_KP_3); +addNumpad("4", KeyTable.XK_4, KeyTable.XK_KP_4); +addNumpad("5", KeyTable.XK_5, KeyTable.XK_KP_5); +addNumpad("6", KeyTable.XK_6, KeyTable.XK_KP_6); +addNumpad("7", KeyTable.XK_7, KeyTable.XK_KP_7); +addNumpad("8", KeyTable.XK_8, KeyTable.XK_KP_8); +addNumpad("9", KeyTable.XK_9, KeyTable.XK_KP_9); + +export default DOMKeyTable; diff --git a/web/public/cloud/vendor/novnc/core/input/fixedkeys.js b/web/public/cloud/vendor/novnc/core/input/fixedkeys.js new file mode 100644 index 00000000..6a922158 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/fixedkeys.js @@ -0,0 +1,129 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +/* + * Fallback mapping between HTML key codes (physical keys) and + * HTML key values. This only works for keys that don't vary + * between layouts. We also omit those who manage fine by mapping the + * Unicode representation. + * + * See https://www.w3.org/TR/uievents-code/ for possible codes. + * See https://www.w3.org/TR/uievents-key/ for possible values. + */ + +/* eslint-disable key-spacing */ + +export default { + +// 3.1.1.1. Writing System Keys + + 'Backspace': 'Backspace', + +// 3.1.1.2. Functional Keys + + 'AltLeft': 'Alt', + 'AltRight': 'Alt', // This could also be 'AltGraph' + 'CapsLock': 'CapsLock', + 'ContextMenu': 'ContextMenu', + 'ControlLeft': 'Control', + 'ControlRight': 'Control', + 'Enter': 'Enter', + 'MetaLeft': 'Meta', + 'MetaRight': 'Meta', + 'ShiftLeft': 'Shift', + 'ShiftRight': 'Shift', + 'Tab': 'Tab', + // FIXME: Japanese/Korean keys + +// 3.1.2. Control Pad Section + + 'Delete': 'Delete', + 'End': 'End', + 'Help': 'Help', + 'Home': 'Home', + 'Insert': 'Insert', + 'PageDown': 'PageDown', + 'PageUp': 'PageUp', + +// 3.1.3. Arrow Pad Section + + 'ArrowDown': 'ArrowDown', + 'ArrowLeft': 'ArrowLeft', + 'ArrowRight': 'ArrowRight', + 'ArrowUp': 'ArrowUp', + +// 3.1.4. Numpad Section + + 'NumLock': 'NumLock', + 'NumpadBackspace': 'Backspace', + 'NumpadClear': 'Clear', + +// 3.1.5. Function Section + + 'Escape': 'Escape', + 'F1': 'F1', + 'F2': 'F2', + 'F3': 'F3', + 'F4': 'F4', + 'F5': 'F5', + 'F6': 'F6', + 'F7': 'F7', + 'F8': 'F8', + 'F9': 'F9', + 'F10': 'F10', + 'F11': 'F11', + 'F12': 'F12', + 'F13': 'F13', + 'F14': 'F14', + 'F15': 'F15', + 'F16': 'F16', + 'F17': 'F17', + 'F18': 'F18', + 'F19': 'F19', + 'F20': 'F20', + 'F21': 'F21', + 'F22': 'F22', + 'F23': 'F23', + 'F24': 'F24', + 'F25': 'F25', + 'F26': 'F26', + 'F27': 'F27', + 'F28': 'F28', + 'F29': 'F29', + 'F30': 'F30', + 'F31': 'F31', + 'F32': 'F32', + 'F33': 'F33', + 'F34': 'F34', + 'F35': 'F35', + 'PrintScreen': 'PrintScreen', + 'ScrollLock': 'ScrollLock', + 'Pause': 'Pause', + +// 3.1.6. Media Keys + + 'BrowserBack': 'BrowserBack', + 'BrowserFavorites': 'BrowserFavorites', + 'BrowserForward': 'BrowserForward', + 'BrowserHome': 'BrowserHome', + 'BrowserRefresh': 'BrowserRefresh', + 'BrowserSearch': 'BrowserSearch', + 'BrowserStop': 'BrowserStop', + 'Eject': 'Eject', + 'LaunchApp1': 'LaunchMyComputer', + 'LaunchApp2': 'LaunchCalendar', + 'LaunchMail': 'LaunchMail', + 'MediaPlayPause': 'MediaPlay', + 'MediaStop': 'MediaStop', + 'MediaTrackNext': 'MediaTrackNext', + 'MediaTrackPrevious': 'MediaTrackPrevious', + 'Power': 'Power', + 'Sleep': 'Sleep', + 'AudioVolumeDown': 'AudioVolumeDown', + 'AudioVolumeMute': 'AudioVolumeMute', + 'AudioVolumeUp': 'AudioVolumeUp', + 'WakeUp': 'WakeUp', +}; diff --git a/web/public/cloud/vendor/novnc/core/input/gesturehandler.js b/web/public/cloud/vendor/novnc/core/input/gesturehandler.js new file mode 100644 index 00000000..b072e01d --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/gesturehandler.js @@ -0,0 +1,567 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +const GH_NOGESTURE = 0; +const GH_ONETAP = 1; +const GH_TWOTAP = 2; +const GH_THREETAP = 4; +const GH_DRAG = 8; +const GH_LONGPRESS = 16; +const GH_TWODRAG = 32; +const GH_PINCH = 64; + +const GH_INITSTATE = 127; + +const GH_MOVE_THRESHOLD = 50; +const GH_ANGLE_THRESHOLD = 90; // Degrees + +// Timeout when waiting for gestures (ms) +const GH_MULTITOUCH_TIMEOUT = 250; + +// Maximum time between press and release for a tap (ms) +const GH_TAP_TIMEOUT = 1000; + +// Timeout when waiting for longpress (ms) +const GH_LONGPRESS_TIMEOUT = 1000; + +// Timeout when waiting to decide between PINCH and TWODRAG (ms) +const GH_TWOTOUCH_TIMEOUT = 50; + +export default class GestureHandler { + constructor() { + this._target = null; + + this._state = GH_INITSTATE; + + this._tracked = []; + this._ignored = []; + + this._waitingRelease = false; + this._releaseStart = 0.0; + + this._longpressTimeoutId = null; + this._twoTouchTimeoutId = null; + + this._boundEventHandler = this._eventHandler.bind(this); + } + + attach(target) { + this.detach(); + + this._target = target; + this._target.addEventListener('touchstart', + this._boundEventHandler); + this._target.addEventListener('touchmove', + this._boundEventHandler); + this._target.addEventListener('touchend', + this._boundEventHandler); + this._target.addEventListener('touchcancel', + this._boundEventHandler); + } + + detach() { + if (!this._target) { + return; + } + + this._stopLongpressTimeout(); + this._stopTwoTouchTimeout(); + + this._target.removeEventListener('touchstart', + this._boundEventHandler); + this._target.removeEventListener('touchmove', + this._boundEventHandler); + this._target.removeEventListener('touchend', + this._boundEventHandler); + this._target.removeEventListener('touchcancel', + this._boundEventHandler); + this._target = null; + } + + _eventHandler(e) { + let fn; + + e.stopPropagation(); + e.preventDefault(); + + switch (e.type) { + case 'touchstart': + fn = this._touchStart; + break; + case 'touchmove': + fn = this._touchMove; + break; + case 'touchend': + case 'touchcancel': + fn = this._touchEnd; + break; + } + + for (let i = 0; i < e.changedTouches.length; i++) { + let touch = e.changedTouches[i]; + fn.call(this, touch.identifier, touch.clientX, touch.clientY); + } + } + + _touchStart(id, x, y) { + // Ignore any new touches if there is already an active gesture, + // or we're in a cleanup state + if (this._hasDetectedGesture() || (this._state === GH_NOGESTURE)) { + this._ignored.push(id); + return; + } + + // Did it take too long between touches that we should no longer + // consider this a single gesture? + if ((this._tracked.length > 0) && + ((Date.now() - this._tracked[0].started) > GH_MULTITOUCH_TIMEOUT)) { + this._state = GH_NOGESTURE; + this._ignored.push(id); + return; + } + + // If we're waiting for fingers to release then we should no longer + // recognize new touches + if (this._waitingRelease) { + this._state = GH_NOGESTURE; + this._ignored.push(id); + return; + } + + this._tracked.push({ + id: id, + started: Date.now(), + active: true, + firstX: x, + firstY: y, + lastX: x, + lastY: y, + angle: 0 + }); + + switch (this._tracked.length) { + case 1: + this._startLongpressTimeout(); + break; + + case 2: + this._state &= ~(GH_ONETAP | GH_DRAG | GH_LONGPRESS); + this._stopLongpressTimeout(); + break; + + case 3: + this._state &= ~(GH_TWOTAP | GH_TWODRAG | GH_PINCH); + break; + + default: + this._state = GH_NOGESTURE; + } + } + + _touchMove(id, x, y) { + let touch = this._tracked.find(t => t.id === id); + + // If this is an update for a touch we're not tracking, ignore it + if (touch === undefined) { + return; + } + + // Update the touches last position with the event coordinates + touch.lastX = x; + touch.lastY = y; + + let deltaX = x - touch.firstX; + let deltaY = y - touch.firstY; + + // Update angle when the touch has moved + if ((touch.firstX !== touch.lastX) || + (touch.firstY !== touch.lastY)) { + touch.angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI; + } + + if (!this._hasDetectedGesture()) { + // Ignore moves smaller than the minimum threshold + if (Math.hypot(deltaX, deltaY) < GH_MOVE_THRESHOLD) { + return; + } + + // Can't be a tap or long press as we've seen movement + this._state &= ~(GH_ONETAP | GH_TWOTAP | GH_THREETAP | GH_LONGPRESS); + this._stopLongpressTimeout(); + + if (this._tracked.length !== 1) { + this._state &= ~(GH_DRAG); + } + if (this._tracked.length !== 2) { + this._state &= ~(GH_TWODRAG | GH_PINCH); + } + + // We need to figure out which of our different two touch gestures + // this might be + if (this._tracked.length === 2) { + + // The other touch is the one where the id doesn't match + let prevTouch = this._tracked.find(t => t.id !== id); + + // How far the previous touch point has moved since start + let prevDeltaMove = Math.hypot(prevTouch.firstX - prevTouch.lastX, + prevTouch.firstY - prevTouch.lastY); + + // We know that the current touch moved far enough, + // but unless both touches moved further than their + // threshold we don't want to disqualify any gestures + if (prevDeltaMove > GH_MOVE_THRESHOLD) { + + // The angle difference between the direction of the touch points + let deltaAngle = Math.abs(touch.angle - prevTouch.angle); + deltaAngle = Math.abs(((deltaAngle + 180) % 360) - 180); + + // PINCH or TWODRAG can be eliminated depending on the angle + if (deltaAngle > GH_ANGLE_THRESHOLD) { + this._state &= ~GH_TWODRAG; + } else { + this._state &= ~GH_PINCH; + } + + if (this._isTwoTouchTimeoutRunning()) { + this._stopTwoTouchTimeout(); + } + } else if (!this._isTwoTouchTimeoutRunning()) { + // We can't determine the gesture right now, let's + // wait and see if more events are on their way + this._startTwoTouchTimeout(); + } + } + + if (!this._hasDetectedGesture()) { + return; + } + + this._pushEvent('gesturestart'); + } + + this._pushEvent('gesturemove'); + } + + _touchEnd(id, x, y) { + // Check if this is an ignored touch + if (this._ignored.indexOf(id) !== -1) { + // Remove this touch from ignored + this._ignored.splice(this._ignored.indexOf(id), 1); + + // And reset the state if there are no more touches + if ((this._ignored.length === 0) && + (this._tracked.length === 0)) { + this._state = GH_INITSTATE; + this._waitingRelease = false; + } + return; + } + + // We got a touchend before the timer triggered, + // this cannot result in a gesture anymore. + if (!this._hasDetectedGesture() && + this._isTwoTouchTimeoutRunning()) { + this._stopTwoTouchTimeout(); + this._state = GH_NOGESTURE; + } + + // Some gestures don't trigger until a touch is released + if (!this._hasDetectedGesture()) { + // Can't be a gesture that relies on movement + this._state &= ~(GH_DRAG | GH_TWODRAG | GH_PINCH); + // Or something that relies on more time + this._state &= ~GH_LONGPRESS; + this._stopLongpressTimeout(); + + if (!this._waitingRelease) { + this._releaseStart = Date.now(); + this._waitingRelease = true; + + // Can't be a tap that requires more touches than we current have + switch (this._tracked.length) { + case 1: + this._state &= ~(GH_TWOTAP | GH_THREETAP); + break; + + case 2: + this._state &= ~(GH_ONETAP | GH_THREETAP); + break; + } + } + } + + // Waiting for all touches to release? (i.e. some tap) + if (this._waitingRelease) { + // Were all touches released at roughly the same time? + if ((Date.now() - this._releaseStart) > GH_MULTITOUCH_TIMEOUT) { + this._state = GH_NOGESTURE; + } + + // Did too long time pass between press and release? + if (this._tracked.some(t => (Date.now() - t.started) > GH_TAP_TIMEOUT)) { + this._state = GH_NOGESTURE; + } + + let touch = this._tracked.find(t => t.id === id); + touch.active = false; + + // Are we still waiting for more releases? + if (this._hasDetectedGesture()) { + this._pushEvent('gesturestart'); + } else { + // Have we reached a dead end? + if (this._state !== GH_NOGESTURE) { + return; + } + } + } + + if (this._hasDetectedGesture()) { + this._pushEvent('gestureend'); + } + + // Ignore any remaining touches until they are ended + for (let i = 0; i < this._tracked.length; i++) { + if (this._tracked[i].active) { + this._ignored.push(this._tracked[i].id); + } + } + this._tracked = []; + + this._state = GH_NOGESTURE; + + // Remove this touch from ignored if it's in there + if (this._ignored.indexOf(id) !== -1) { + this._ignored.splice(this._ignored.indexOf(id), 1); + } + + // We reset the state if ignored is empty + if ((this._ignored.length === 0)) { + this._state = GH_INITSTATE; + this._waitingRelease = false; + } + } + + _hasDetectedGesture() { + if (this._state === GH_NOGESTURE) { + return false; + } + // Check to see if the bitmask value is a power of 2 + // (i.e. only one bit set). If it is, we have a state. + if (this._state & (this._state - 1)) { + return false; + } + + // For taps we also need to have all touches released + // before we've fully detected the gesture + if (this._state & (GH_ONETAP | GH_TWOTAP | GH_THREETAP)) { + if (this._tracked.some(t => t.active)) { + return false; + } + } + + return true; + } + + _startLongpressTimeout() { + this._stopLongpressTimeout(); + this._longpressTimeoutId = setTimeout(() => this._longpressTimeout(), + GH_LONGPRESS_TIMEOUT); + } + + _stopLongpressTimeout() { + clearTimeout(this._longpressTimeoutId); + this._longpressTimeoutId = null; + } + + _longpressTimeout() { + if (this._hasDetectedGesture()) { + throw new Error("A longpress gesture failed, conflict with a different gesture"); + } + + this._state = GH_LONGPRESS; + this._pushEvent('gesturestart'); + } + + _startTwoTouchTimeout() { + this._stopTwoTouchTimeout(); + this._twoTouchTimeoutId = setTimeout(() => this._twoTouchTimeout(), + GH_TWOTOUCH_TIMEOUT); + } + + _stopTwoTouchTimeout() { + clearTimeout(this._twoTouchTimeoutId); + this._twoTouchTimeoutId = null; + } + + _isTwoTouchTimeoutRunning() { + return this._twoTouchTimeoutId !== null; + } + + _twoTouchTimeout() { + if (this._tracked.length === 0) { + throw new Error("A pinch or two drag gesture failed, no tracked touches"); + } + + // How far each touch point has moved since start + let avgM = this._getAverageMovement(); + let avgMoveH = Math.abs(avgM.x); + let avgMoveV = Math.abs(avgM.y); + + // The difference in the distance between where + // the touch points started and where they are now + let avgD = this._getAverageDistance(); + let deltaTouchDistance = Math.abs(Math.hypot(avgD.first.x, avgD.first.y) - + Math.hypot(avgD.last.x, avgD.last.y)); + + if ((avgMoveV < deltaTouchDistance) && + (avgMoveH < deltaTouchDistance)) { + this._state = GH_PINCH; + } else { + this._state = GH_TWODRAG; + } + + this._pushEvent('gesturestart'); + this._pushEvent('gesturemove'); + } + + _pushEvent(type) { + let detail = { type: this._stateToGesture(this._state) }; + + // For most gesture events the current (average) position is the + // most useful + let avg = this._getPosition(); + let pos = avg.last; + + // However we have a slight distance to detect gestures, so for the + // first gesture event we want to use the first positions we saw + if (type === 'gesturestart') { + pos = avg.first; + } + + // For these gestures, we always want the event coordinates + // to be where the gesture began, not the current touch location. + switch (this._state) { + case GH_TWODRAG: + case GH_PINCH: + pos = avg.first; + break; + } + + detail['clientX'] = pos.x; + detail['clientY'] = pos.y; + + // FIXME: other coordinates? + + // Some gestures also have a magnitude + if (this._state === GH_PINCH) { + let distance = this._getAverageDistance(); + if (type === 'gesturestart') { + detail['magnitudeX'] = distance.first.x; + detail['magnitudeY'] = distance.first.y; + } else { + detail['magnitudeX'] = distance.last.x; + detail['magnitudeY'] = distance.last.y; + } + } else if (this._state === GH_TWODRAG) { + if (type === 'gesturestart') { + detail['magnitudeX'] = 0.0; + detail['magnitudeY'] = 0.0; + } else { + let movement = this._getAverageMovement(); + detail['magnitudeX'] = movement.x; + detail['magnitudeY'] = movement.y; + } + } + + let gev = new CustomEvent(type, { detail: detail }); + this._target.dispatchEvent(gev); + } + + _stateToGesture(state) { + switch (state) { + case GH_ONETAP: + return 'onetap'; + case GH_TWOTAP: + return 'twotap'; + case GH_THREETAP: + return 'threetap'; + case GH_DRAG: + return 'drag'; + case GH_LONGPRESS: + return 'longpress'; + case GH_TWODRAG: + return 'twodrag'; + case GH_PINCH: + return 'pinch'; + } + + throw new Error("Unknown gesture state: " + state); + } + + _getPosition() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture position, no tracked touches"); + } + + let size = this._tracked.length; + let fx = 0, fy = 0, lx = 0, ly = 0; + + for (let i = 0; i < this._tracked.length; i++) { + fx += this._tracked[i].firstX; + fy += this._tracked[i].firstY; + lx += this._tracked[i].lastX; + ly += this._tracked[i].lastY; + } + + return { first: { x: fx / size, + y: fy / size }, + last: { x: lx / size, + y: ly / size } }; + } + + _getAverageMovement() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture movement, no tracked touches"); + } + + let totalH, totalV; + totalH = totalV = 0; + let size = this._tracked.length; + + for (let i = 0; i < this._tracked.length; i++) { + totalH += this._tracked[i].lastX - this._tracked[i].firstX; + totalV += this._tracked[i].lastY - this._tracked[i].firstY; + } + + return { x: totalH / size, + y: totalV / size }; + } + + _getAverageDistance() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture distance, no tracked touches"); + } + + // Distance between the first and last tracked touches + + let first = this._tracked[0]; + let last = this._tracked[this._tracked.length - 1]; + + let fdx = Math.abs(last.firstX - first.firstX); + let fdy = Math.abs(last.firstY - first.firstY); + + let ldx = Math.abs(last.lastX - first.lastX); + let ldy = Math.abs(last.lastY - first.lastY); + + return { first: { x: fdx, y: fdy }, + last: { x: ldx, y: ldy } }; + } +} diff --git a/web/public/cloud/vendor/novnc/core/input/keyboard.js b/web/public/cloud/vendor/novnc/core/input/keyboard.js new file mode 100644 index 00000000..3cc89174 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/keyboard.js @@ -0,0 +1,294 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +import * as Log from '../util/logging.js'; +import { stopEvent } from '../util/events.js'; +import * as KeyboardUtil from "./util.js"; +import KeyTable from "./keysym.js"; +import * as browser from "../util/browser.js"; + +// +// Keyboard event handler +// + +export default class Keyboard { + constructor(target) { + this._target = target || null; + + this._keyDownList = {}; // List of depressed keys + // (even if they are happy) + this._altGrArmed = false; // Windows AltGr detection + + // keep these here so we can refer to them later + this._eventHandlers = { + 'keyup': this._handleKeyUp.bind(this), + 'keydown': this._handleKeyDown.bind(this), + 'blur': this._allKeysUp.bind(this), + }; + + // ===== EVENT HANDLERS ===== + + this.onkeyevent = () => {}; // Handler for key press/release + } + + // ===== PRIVATE METHODS ===== + + _sendKeyEvent(keysym, code, down, numlock = null, capslock = null) { + if (down) { + this._keyDownList[code] = keysym; + } else { + // Do we really think this key is down? + if (!(code in this._keyDownList)) { + return; + } + delete this._keyDownList[code]; + } + + Log.Debug("onkeyevent " + (down ? "down" : "up") + + ", keysym: " + keysym, ", code: " + code + + ", numlock: " + numlock + ", capslock: " + capslock); + this.onkeyevent(keysym, code, down, numlock, capslock); + } + + _getKeyCode(e) { + const code = KeyboardUtil.getKeycode(e); + if (code !== 'Unidentified') { + return code; + } + + // Unstable, but we don't have anything else to go on + if (e.keyCode) { + // 229 is used for composition events + if (e.keyCode !== 229) { + return 'Platform' + e.keyCode; + } + } + + // A precursor to the final DOM3 standard. Unfortunately it + // is not layout independent, so it is as bad as using keyCode + if (e.keyIdentifier) { + // Non-character key? + if (e.keyIdentifier.substr(0, 2) !== 'U+') { + return e.keyIdentifier; + } + + const codepoint = parseInt(e.keyIdentifier.substr(2), 16); + const char = String.fromCharCode(codepoint).toUpperCase(); + + return 'Platform' + char.charCodeAt(); + } + + return 'Unidentified'; + } + + _handleKeyDown(e) { + const code = this._getKeyCode(e); + let keysym = KeyboardUtil.getKeysym(e); + let numlock = e.getModifierState('NumLock'); + let capslock = e.getModifierState('CapsLock'); + + // getModifierState for NumLock is not supported on mac and ios and always returns false. + // Set to null to indicate unknown/unsupported instead. + if (browser.isMac() || browser.isIOS()) { + numlock = null; + } + + // Windows doesn't have a proper AltGr, but handles it using + // fake Ctrl+Alt. However the remote end might not be Windows, + // so we need to merge those in to a single AltGr event. We + // detect this case by seeing the two key events directly after + // each other with a very short time between them (<50ms). + if (this._altGrArmed) { + this._altGrArmed = false; + clearTimeout(this._altGrTimeout); + + if ((code === "AltRight") && + ((e.timeStamp - this._altGrCtrlTime) < 50)) { + // FIXME: We fail to detect this if either Ctrl key is + // first manually pressed as Windows then no + // longer sends the fake Ctrl down event. It + // does however happily send real Ctrl events + // even when AltGr is already down. Some + // browsers detect this for us though and set the + // key to "AltGraph". + keysym = KeyTable.XK_ISO_Level3_Shift; + } else { + this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true, numlock, capslock); + } + } + + // We cannot handle keys we cannot track, but we also need + // to deal with virtual keyboards which omit key info + if (code === 'Unidentified') { + if (keysym) { + // If it's a virtual keyboard then it should be + // sufficient to just send press and release right + // after each other + this._sendKeyEvent(keysym, code, true, numlock, capslock); + this._sendKeyEvent(keysym, code, false, numlock, capslock); + } + + stopEvent(e); + return; + } + + // Alt behaves more like AltGraph on macOS, so shuffle the + // keys around a bit to make things more sane for the remote + // server. This method is used by RealVNC and TigerVNC (and + // possibly others). + if (browser.isMac() || browser.isIOS()) { + switch (keysym) { + case KeyTable.XK_Super_L: + keysym = KeyTable.XK_Alt_L; + break; + case KeyTable.XK_Super_R: + keysym = KeyTable.XK_Super_L; + break; + case KeyTable.XK_Alt_L: + keysym = KeyTable.XK_Mode_switch; + break; + case KeyTable.XK_Alt_R: + keysym = KeyTable.XK_ISO_Level3_Shift; + break; + } + } + + // Is this key already pressed? If so, then we must use the + // same keysym or we'll confuse the server + if (code in this._keyDownList) { + keysym = this._keyDownList[code]; + } + + // macOS doesn't send proper key releases if a key is pressed + // while meta is held down + if ((browser.isMac() || browser.isIOS()) && + (e.metaKey && code !== 'MetaLeft' && code !== 'MetaRight')) { + this._sendKeyEvent(keysym, code, true, numlock, capslock); + this._sendKeyEvent(keysym, code, false, numlock, capslock); + stopEvent(e); + return; + } + + // macOS doesn't send proper key events for modifiers, only + // state change events. That gets extra confusing for CapsLock + // which toggles on each press, but not on release. So pretend + // it was a quick press and release of the button. + if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) { + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true, numlock, capslock); + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false, numlock, capslock); + stopEvent(e); + return; + } + + // Windows doesn't send proper key releases for a bunch of + // Japanese IM keys so we have to fake the release right away + const jpBadKeys = [ KeyTable.XK_Zenkaku_Hankaku, + KeyTable.XK_Eisu_toggle, + KeyTable.XK_Katakana, + KeyTable.XK_Hiragana, + KeyTable.XK_Romaji ]; + if (browser.isWindows() && jpBadKeys.includes(keysym)) { + this._sendKeyEvent(keysym, code, true, numlock, capslock); + this._sendKeyEvent(keysym, code, false, numlock, capslock); + stopEvent(e); + return; + } + + stopEvent(e); + + // Possible start of AltGr sequence? (see above) + if ((code === "ControlLeft") && browser.isWindows() && + !("ControlLeft" in this._keyDownList)) { + this._altGrArmed = true; + this._altGrTimeout = setTimeout(this._interruptAltGrSequence.bind(this), 100); + this._altGrCtrlTime = e.timeStamp; + return; + } + + this._sendKeyEvent(keysym, code, true, numlock, capslock); + } + + _handleKeyUp(e) { + stopEvent(e); + + const code = this._getKeyCode(e); + + // We can't get a release in the middle of an AltGr sequence, so + // abort that detection + this._interruptAltGrSequence(); + + // See comment in _handleKeyDown() + if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) { + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true); + this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false); + return; + } + + this._sendKeyEvent(this._keyDownList[code], code, false); + + // Windows has a rather nasty bug where it won't send key + // release events for a Shift button if the other Shift is still + // pressed + if (browser.isWindows() && ((code === 'ShiftLeft') || + (code === 'ShiftRight'))) { + if ('ShiftRight' in this._keyDownList) { + this._sendKeyEvent(this._keyDownList['ShiftRight'], + 'ShiftRight', false); + } + if ('ShiftLeft' in this._keyDownList) { + this._sendKeyEvent(this._keyDownList['ShiftLeft'], + 'ShiftLeft', false); + } + } + } + + _interruptAltGrSequence() { + if (this._altGrArmed) { + this._altGrArmed = false; + clearTimeout(this._altGrTimeout); + this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); + } + } + + _allKeysUp() { + Log.Debug(">> Keyboard.allKeysUp"); + + // Prevent control key being processed after losing focus. + this._interruptAltGrSequence(); + + for (let code in this._keyDownList) { + this._sendKeyEvent(this._keyDownList[code], code, false); + } + Log.Debug("<< Keyboard.allKeysUp"); + } + + // ===== PUBLIC METHODS ===== + + grab() { + //Log.Debug(">> Keyboard.grab"); + + this._target.addEventListener('keydown', this._eventHandlers.keydown); + this._target.addEventListener('keyup', this._eventHandlers.keyup); + + // Release (key up) if window loses focus + window.addEventListener('blur', this._eventHandlers.blur); + + //Log.Debug("<< Keyboard.grab"); + } + + ungrab() { + //Log.Debug(">> Keyboard.ungrab"); + + this._target.removeEventListener('keydown', this._eventHandlers.keydown); + this._target.removeEventListener('keyup', this._eventHandlers.keyup); + window.removeEventListener('blur', this._eventHandlers.blur); + + // Release (key up) all keys that are in a down state + this._allKeysUp(); + + //Log.Debug(">> Keyboard.ungrab"); + } +} diff --git a/web/public/cloud/vendor/novnc/core/input/keysym.js b/web/public/cloud/vendor/novnc/core/input/keysym.js new file mode 100644 index 00000000..22ba0584 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/keysym.js @@ -0,0 +1,616 @@ +/* eslint-disable key-spacing */ + +export default { + XK_VoidSymbol: 0xffffff, /* Void symbol */ + + XK_BackSpace: 0xff08, /* Back space, back char */ + XK_Tab: 0xff09, + XK_Linefeed: 0xff0a, /* Linefeed, LF */ + XK_Clear: 0xff0b, + XK_Return: 0xff0d, /* Return, enter */ + XK_Pause: 0xff13, /* Pause, hold */ + XK_Scroll_Lock: 0xff14, + XK_Sys_Req: 0xff15, + XK_Escape: 0xff1b, + XK_Delete: 0xffff, /* Delete, rubout */ + + /* International & multi-key character composition */ + + XK_Multi_key: 0xff20, /* Multi-key character compose */ + XK_Codeinput: 0xff37, + XK_SingleCandidate: 0xff3c, + XK_MultipleCandidate: 0xff3d, + XK_PreviousCandidate: 0xff3e, + + /* Japanese keyboard support */ + + XK_Kanji: 0xff21, /* Kanji, Kanji convert */ + XK_Muhenkan: 0xff22, /* Cancel Conversion */ + XK_Henkan_Mode: 0xff23, /* Start/Stop Conversion */ + XK_Henkan: 0xff23, /* Alias for Henkan_Mode */ + XK_Romaji: 0xff24, /* to Romaji */ + XK_Hiragana: 0xff25, /* to Hiragana */ + XK_Katakana: 0xff26, /* to Katakana */ + XK_Hiragana_Katakana: 0xff27, /* Hiragana/Katakana toggle */ + XK_Zenkaku: 0xff28, /* to Zenkaku */ + XK_Hankaku: 0xff29, /* to Hankaku */ + XK_Zenkaku_Hankaku: 0xff2a, /* Zenkaku/Hankaku toggle */ + XK_Touroku: 0xff2b, /* Add to Dictionary */ + XK_Massyo: 0xff2c, /* Delete from Dictionary */ + XK_Kana_Lock: 0xff2d, /* Kana Lock */ + XK_Kana_Shift: 0xff2e, /* Kana Shift */ + XK_Eisu_Shift: 0xff2f, /* Alphanumeric Shift */ + XK_Eisu_toggle: 0xff30, /* Alphanumeric toggle */ + XK_Kanji_Bangou: 0xff37, /* Codeinput */ + XK_Zen_Koho: 0xff3d, /* Multiple/All Candidate(s) */ + XK_Mae_Koho: 0xff3e, /* Previous Candidate */ + + /* Cursor control & motion */ + + XK_Home: 0xff50, + XK_Left: 0xff51, /* Move left, left arrow */ + XK_Up: 0xff52, /* Move up, up arrow */ + XK_Right: 0xff53, /* Move right, right arrow */ + XK_Down: 0xff54, /* Move down, down arrow */ + XK_Prior: 0xff55, /* Prior, previous */ + XK_Page_Up: 0xff55, + XK_Next: 0xff56, /* Next */ + XK_Page_Down: 0xff56, + XK_End: 0xff57, /* EOL */ + XK_Begin: 0xff58, /* BOL */ + + + /* Misc functions */ + + XK_Select: 0xff60, /* Select, mark */ + XK_Print: 0xff61, + XK_Execute: 0xff62, /* Execute, run, do */ + XK_Insert: 0xff63, /* Insert, insert here */ + XK_Undo: 0xff65, + XK_Redo: 0xff66, /* Redo, again */ + XK_Menu: 0xff67, + XK_Find: 0xff68, /* Find, search */ + XK_Cancel: 0xff69, /* Cancel, stop, abort, exit */ + XK_Help: 0xff6a, /* Help */ + XK_Break: 0xff6b, + XK_Mode_switch: 0xff7e, /* Character set switch */ + XK_script_switch: 0xff7e, /* Alias for mode_switch */ + XK_Num_Lock: 0xff7f, + + /* Keypad functions, keypad numbers cleverly chosen to map to ASCII */ + + XK_KP_Space: 0xff80, /* Space */ + XK_KP_Tab: 0xff89, + XK_KP_Enter: 0xff8d, /* Enter */ + XK_KP_F1: 0xff91, /* PF1, KP_A, ... */ + XK_KP_F2: 0xff92, + XK_KP_F3: 0xff93, + XK_KP_F4: 0xff94, + XK_KP_Home: 0xff95, + XK_KP_Left: 0xff96, + XK_KP_Up: 0xff97, + XK_KP_Right: 0xff98, + XK_KP_Down: 0xff99, + XK_KP_Prior: 0xff9a, + XK_KP_Page_Up: 0xff9a, + XK_KP_Next: 0xff9b, + XK_KP_Page_Down: 0xff9b, + XK_KP_End: 0xff9c, + XK_KP_Begin: 0xff9d, + XK_KP_Insert: 0xff9e, + XK_KP_Delete: 0xff9f, + XK_KP_Equal: 0xffbd, /* Equals */ + XK_KP_Multiply: 0xffaa, + XK_KP_Add: 0xffab, + XK_KP_Separator: 0xffac, /* Separator, often comma */ + XK_KP_Subtract: 0xffad, + XK_KP_Decimal: 0xffae, + XK_KP_Divide: 0xffaf, + + XK_KP_0: 0xffb0, + XK_KP_1: 0xffb1, + XK_KP_2: 0xffb2, + XK_KP_3: 0xffb3, + XK_KP_4: 0xffb4, + XK_KP_5: 0xffb5, + XK_KP_6: 0xffb6, + XK_KP_7: 0xffb7, + XK_KP_8: 0xffb8, + XK_KP_9: 0xffb9, + + /* + * Auxiliary functions; note the duplicate definitions for left and right + * function keys; Sun keyboards and a few other manufacturers have such + * function key groups on the left and/or right sides of the keyboard. + * We've not found a keyboard with more than 35 function keys total. + */ + + XK_F1: 0xffbe, + XK_F2: 0xffbf, + XK_F3: 0xffc0, + XK_F4: 0xffc1, + XK_F5: 0xffc2, + XK_F6: 0xffc3, + XK_F7: 0xffc4, + XK_F8: 0xffc5, + XK_F9: 0xffc6, + XK_F10: 0xffc7, + XK_F11: 0xffc8, + XK_L1: 0xffc8, + XK_F12: 0xffc9, + XK_L2: 0xffc9, + XK_F13: 0xffca, + XK_L3: 0xffca, + XK_F14: 0xffcb, + XK_L4: 0xffcb, + XK_F15: 0xffcc, + XK_L5: 0xffcc, + XK_F16: 0xffcd, + XK_L6: 0xffcd, + XK_F17: 0xffce, + XK_L7: 0xffce, + XK_F18: 0xffcf, + XK_L8: 0xffcf, + XK_F19: 0xffd0, + XK_L9: 0xffd0, + XK_F20: 0xffd1, + XK_L10: 0xffd1, + XK_F21: 0xffd2, + XK_R1: 0xffd2, + XK_F22: 0xffd3, + XK_R2: 0xffd3, + XK_F23: 0xffd4, + XK_R3: 0xffd4, + XK_F24: 0xffd5, + XK_R4: 0xffd5, + XK_F25: 0xffd6, + XK_R5: 0xffd6, + XK_F26: 0xffd7, + XK_R6: 0xffd7, + XK_F27: 0xffd8, + XK_R7: 0xffd8, + XK_F28: 0xffd9, + XK_R8: 0xffd9, + XK_F29: 0xffda, + XK_R9: 0xffda, + XK_F30: 0xffdb, + XK_R10: 0xffdb, + XK_F31: 0xffdc, + XK_R11: 0xffdc, + XK_F32: 0xffdd, + XK_R12: 0xffdd, + XK_F33: 0xffde, + XK_R13: 0xffde, + XK_F34: 0xffdf, + XK_R14: 0xffdf, + XK_F35: 0xffe0, + XK_R15: 0xffe0, + + /* Modifiers */ + + XK_Shift_L: 0xffe1, /* Left shift */ + XK_Shift_R: 0xffe2, /* Right shift */ + XK_Control_L: 0xffe3, /* Left control */ + XK_Control_R: 0xffe4, /* Right control */ + XK_Caps_Lock: 0xffe5, /* Caps lock */ + XK_Shift_Lock: 0xffe6, /* Shift lock */ + + XK_Meta_L: 0xffe7, /* Left meta */ + XK_Meta_R: 0xffe8, /* Right meta */ + XK_Alt_L: 0xffe9, /* Left alt */ + XK_Alt_R: 0xffea, /* Right alt */ + XK_Super_L: 0xffeb, /* Left super */ + XK_Super_R: 0xffec, /* Right super */ + XK_Hyper_L: 0xffed, /* Left hyper */ + XK_Hyper_R: 0xffee, /* Right hyper */ + + /* + * Keyboard (XKB) Extension function and modifier keys + * (from Appendix C of "The X Keyboard Extension: Protocol Specification") + * Byte 3 = 0xfe + */ + + XK_ISO_Level3_Shift: 0xfe03, /* AltGr */ + XK_ISO_Next_Group: 0xfe08, + XK_ISO_Prev_Group: 0xfe0a, + XK_ISO_First_Group: 0xfe0c, + XK_ISO_Last_Group: 0xfe0e, + + /* + * Latin 1 + * (ISO/IEC 8859-1: Unicode U+0020..U+00FF) + * Byte 3: 0 + */ + + XK_space: 0x0020, /* U+0020 SPACE */ + XK_exclam: 0x0021, /* U+0021 EXCLAMATION MARK */ + XK_quotedbl: 0x0022, /* U+0022 QUOTATION MARK */ + XK_numbersign: 0x0023, /* U+0023 NUMBER SIGN */ + XK_dollar: 0x0024, /* U+0024 DOLLAR SIGN */ + XK_percent: 0x0025, /* U+0025 PERCENT SIGN */ + XK_ampersand: 0x0026, /* U+0026 AMPERSAND */ + XK_apostrophe: 0x0027, /* U+0027 APOSTROPHE */ + XK_quoteright: 0x0027, /* deprecated */ + XK_parenleft: 0x0028, /* U+0028 LEFT PARENTHESIS */ + XK_parenright: 0x0029, /* U+0029 RIGHT PARENTHESIS */ + XK_asterisk: 0x002a, /* U+002A ASTERISK */ + XK_plus: 0x002b, /* U+002B PLUS SIGN */ + XK_comma: 0x002c, /* U+002C COMMA */ + XK_minus: 0x002d, /* U+002D HYPHEN-MINUS */ + XK_period: 0x002e, /* U+002E FULL STOP */ + XK_slash: 0x002f, /* U+002F SOLIDUS */ + XK_0: 0x0030, /* U+0030 DIGIT ZERO */ + XK_1: 0x0031, /* U+0031 DIGIT ONE */ + XK_2: 0x0032, /* U+0032 DIGIT TWO */ + XK_3: 0x0033, /* U+0033 DIGIT THREE */ + XK_4: 0x0034, /* U+0034 DIGIT FOUR */ + XK_5: 0x0035, /* U+0035 DIGIT FIVE */ + XK_6: 0x0036, /* U+0036 DIGIT SIX */ + XK_7: 0x0037, /* U+0037 DIGIT SEVEN */ + XK_8: 0x0038, /* U+0038 DIGIT EIGHT */ + XK_9: 0x0039, /* U+0039 DIGIT NINE */ + XK_colon: 0x003a, /* U+003A COLON */ + XK_semicolon: 0x003b, /* U+003B SEMICOLON */ + XK_less: 0x003c, /* U+003C LESS-THAN SIGN */ + XK_equal: 0x003d, /* U+003D EQUALS SIGN */ + XK_greater: 0x003e, /* U+003E GREATER-THAN SIGN */ + XK_question: 0x003f, /* U+003F QUESTION MARK */ + XK_at: 0x0040, /* U+0040 COMMERCIAL AT */ + XK_A: 0x0041, /* U+0041 LATIN CAPITAL LETTER A */ + XK_B: 0x0042, /* U+0042 LATIN CAPITAL LETTER B */ + XK_C: 0x0043, /* U+0043 LATIN CAPITAL LETTER C */ + XK_D: 0x0044, /* U+0044 LATIN CAPITAL LETTER D */ + XK_E: 0x0045, /* U+0045 LATIN CAPITAL LETTER E */ + XK_F: 0x0046, /* U+0046 LATIN CAPITAL LETTER F */ + XK_G: 0x0047, /* U+0047 LATIN CAPITAL LETTER G */ + XK_H: 0x0048, /* U+0048 LATIN CAPITAL LETTER H */ + XK_I: 0x0049, /* U+0049 LATIN CAPITAL LETTER I */ + XK_J: 0x004a, /* U+004A LATIN CAPITAL LETTER J */ + XK_K: 0x004b, /* U+004B LATIN CAPITAL LETTER K */ + XK_L: 0x004c, /* U+004C LATIN CAPITAL LETTER L */ + XK_M: 0x004d, /* U+004D LATIN CAPITAL LETTER M */ + XK_N: 0x004e, /* U+004E LATIN CAPITAL LETTER N */ + XK_O: 0x004f, /* U+004F LATIN CAPITAL LETTER O */ + XK_P: 0x0050, /* U+0050 LATIN CAPITAL LETTER P */ + XK_Q: 0x0051, /* U+0051 LATIN CAPITAL LETTER Q */ + XK_R: 0x0052, /* U+0052 LATIN CAPITAL LETTER R */ + XK_S: 0x0053, /* U+0053 LATIN CAPITAL LETTER S */ + XK_T: 0x0054, /* U+0054 LATIN CAPITAL LETTER T */ + XK_U: 0x0055, /* U+0055 LATIN CAPITAL LETTER U */ + XK_V: 0x0056, /* U+0056 LATIN CAPITAL LETTER V */ + XK_W: 0x0057, /* U+0057 LATIN CAPITAL LETTER W */ + XK_X: 0x0058, /* U+0058 LATIN CAPITAL LETTER X */ + XK_Y: 0x0059, /* U+0059 LATIN CAPITAL LETTER Y */ + XK_Z: 0x005a, /* U+005A LATIN CAPITAL LETTER Z */ + XK_bracketleft: 0x005b, /* U+005B LEFT SQUARE BRACKET */ + XK_backslash: 0x005c, /* U+005C REVERSE SOLIDUS */ + XK_bracketright: 0x005d, /* U+005D RIGHT SQUARE BRACKET */ + XK_asciicircum: 0x005e, /* U+005E CIRCUMFLEX ACCENT */ + XK_underscore: 0x005f, /* U+005F LOW LINE */ + XK_grave: 0x0060, /* U+0060 GRAVE ACCENT */ + XK_quoteleft: 0x0060, /* deprecated */ + XK_a: 0x0061, /* U+0061 LATIN SMALL LETTER A */ + XK_b: 0x0062, /* U+0062 LATIN SMALL LETTER B */ + XK_c: 0x0063, /* U+0063 LATIN SMALL LETTER C */ + XK_d: 0x0064, /* U+0064 LATIN SMALL LETTER D */ + XK_e: 0x0065, /* U+0065 LATIN SMALL LETTER E */ + XK_f: 0x0066, /* U+0066 LATIN SMALL LETTER F */ + XK_g: 0x0067, /* U+0067 LATIN SMALL LETTER G */ + XK_h: 0x0068, /* U+0068 LATIN SMALL LETTER H */ + XK_i: 0x0069, /* U+0069 LATIN SMALL LETTER I */ + XK_j: 0x006a, /* U+006A LATIN SMALL LETTER J */ + XK_k: 0x006b, /* U+006B LATIN SMALL LETTER K */ + XK_l: 0x006c, /* U+006C LATIN SMALL LETTER L */ + XK_m: 0x006d, /* U+006D LATIN SMALL LETTER M */ + XK_n: 0x006e, /* U+006E LATIN SMALL LETTER N */ + XK_o: 0x006f, /* U+006F LATIN SMALL LETTER O */ + XK_p: 0x0070, /* U+0070 LATIN SMALL LETTER P */ + XK_q: 0x0071, /* U+0071 LATIN SMALL LETTER Q */ + XK_r: 0x0072, /* U+0072 LATIN SMALL LETTER R */ + XK_s: 0x0073, /* U+0073 LATIN SMALL LETTER S */ + XK_t: 0x0074, /* U+0074 LATIN SMALL LETTER T */ + XK_u: 0x0075, /* U+0075 LATIN SMALL LETTER U */ + XK_v: 0x0076, /* U+0076 LATIN SMALL LETTER V */ + XK_w: 0x0077, /* U+0077 LATIN SMALL LETTER W */ + XK_x: 0x0078, /* U+0078 LATIN SMALL LETTER X */ + XK_y: 0x0079, /* U+0079 LATIN SMALL LETTER Y */ + XK_z: 0x007a, /* U+007A LATIN SMALL LETTER Z */ + XK_braceleft: 0x007b, /* U+007B LEFT CURLY BRACKET */ + XK_bar: 0x007c, /* U+007C VERTICAL LINE */ + XK_braceright: 0x007d, /* U+007D RIGHT CURLY BRACKET */ + XK_asciitilde: 0x007e, /* U+007E TILDE */ + + XK_nobreakspace: 0x00a0, /* U+00A0 NO-BREAK SPACE */ + XK_exclamdown: 0x00a1, /* U+00A1 INVERTED EXCLAMATION MARK */ + XK_cent: 0x00a2, /* U+00A2 CENT SIGN */ + XK_sterling: 0x00a3, /* U+00A3 POUND SIGN */ + XK_currency: 0x00a4, /* U+00A4 CURRENCY SIGN */ + XK_yen: 0x00a5, /* U+00A5 YEN SIGN */ + XK_brokenbar: 0x00a6, /* U+00A6 BROKEN BAR */ + XK_section: 0x00a7, /* U+00A7 SECTION SIGN */ + XK_diaeresis: 0x00a8, /* U+00A8 DIAERESIS */ + XK_copyright: 0x00a9, /* U+00A9 COPYRIGHT SIGN */ + XK_ordfeminine: 0x00aa, /* U+00AA FEMININE ORDINAL INDICATOR */ + XK_guillemotleft: 0x00ab, /* U+00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */ + XK_notsign: 0x00ac, /* U+00AC NOT SIGN */ + XK_hyphen: 0x00ad, /* U+00AD SOFT HYPHEN */ + XK_registered: 0x00ae, /* U+00AE REGISTERED SIGN */ + XK_macron: 0x00af, /* U+00AF MACRON */ + XK_degree: 0x00b0, /* U+00B0 DEGREE SIGN */ + XK_plusminus: 0x00b1, /* U+00B1 PLUS-MINUS SIGN */ + XK_twosuperior: 0x00b2, /* U+00B2 SUPERSCRIPT TWO */ + XK_threesuperior: 0x00b3, /* U+00B3 SUPERSCRIPT THREE */ + XK_acute: 0x00b4, /* U+00B4 ACUTE ACCENT */ + XK_mu: 0x00b5, /* U+00B5 MICRO SIGN */ + XK_paragraph: 0x00b6, /* U+00B6 PILCROW SIGN */ + XK_periodcentered: 0x00b7, /* U+00B7 MIDDLE DOT */ + XK_cedilla: 0x00b8, /* U+00B8 CEDILLA */ + XK_onesuperior: 0x00b9, /* U+00B9 SUPERSCRIPT ONE */ + XK_masculine: 0x00ba, /* U+00BA MASCULINE ORDINAL INDICATOR */ + XK_guillemotright: 0x00bb, /* U+00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */ + XK_onequarter: 0x00bc, /* U+00BC VULGAR FRACTION ONE QUARTER */ + XK_onehalf: 0x00bd, /* U+00BD VULGAR FRACTION ONE HALF */ + XK_threequarters: 0x00be, /* U+00BE VULGAR FRACTION THREE QUARTERS */ + XK_questiondown: 0x00bf, /* U+00BF INVERTED QUESTION MARK */ + XK_Agrave: 0x00c0, /* U+00C0 LATIN CAPITAL LETTER A WITH GRAVE */ + XK_Aacute: 0x00c1, /* U+00C1 LATIN CAPITAL LETTER A WITH ACUTE */ + XK_Acircumflex: 0x00c2, /* U+00C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */ + XK_Atilde: 0x00c3, /* U+00C3 LATIN CAPITAL LETTER A WITH TILDE */ + XK_Adiaeresis: 0x00c4, /* U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS */ + XK_Aring: 0x00c5, /* U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE */ + XK_AE: 0x00c6, /* U+00C6 LATIN CAPITAL LETTER AE */ + XK_Ccedilla: 0x00c7, /* U+00C7 LATIN CAPITAL LETTER C WITH CEDILLA */ + XK_Egrave: 0x00c8, /* U+00C8 LATIN CAPITAL LETTER E WITH GRAVE */ + XK_Eacute: 0x00c9, /* U+00C9 LATIN CAPITAL LETTER E WITH ACUTE */ + XK_Ecircumflex: 0x00ca, /* U+00CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX */ + XK_Ediaeresis: 0x00cb, /* U+00CB LATIN CAPITAL LETTER E WITH DIAERESIS */ + XK_Igrave: 0x00cc, /* U+00CC LATIN CAPITAL LETTER I WITH GRAVE */ + XK_Iacute: 0x00cd, /* U+00CD LATIN CAPITAL LETTER I WITH ACUTE */ + XK_Icircumflex: 0x00ce, /* U+00CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX */ + XK_Idiaeresis: 0x00cf, /* U+00CF LATIN CAPITAL LETTER I WITH DIAERESIS */ + XK_ETH: 0x00d0, /* U+00D0 LATIN CAPITAL LETTER ETH */ + XK_Eth: 0x00d0, /* deprecated */ + XK_Ntilde: 0x00d1, /* U+00D1 LATIN CAPITAL LETTER N WITH TILDE */ + XK_Ograve: 0x00d2, /* U+00D2 LATIN CAPITAL LETTER O WITH GRAVE */ + XK_Oacute: 0x00d3, /* U+00D3 LATIN CAPITAL LETTER O WITH ACUTE */ + XK_Ocircumflex: 0x00d4, /* U+00D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX */ + XK_Otilde: 0x00d5, /* U+00D5 LATIN CAPITAL LETTER O WITH TILDE */ + XK_Odiaeresis: 0x00d6, /* U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS */ + XK_multiply: 0x00d7, /* U+00D7 MULTIPLICATION SIGN */ + XK_Oslash: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ + XK_Ooblique: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ + XK_Ugrave: 0x00d9, /* U+00D9 LATIN CAPITAL LETTER U WITH GRAVE */ + XK_Uacute: 0x00da, /* U+00DA LATIN CAPITAL LETTER U WITH ACUTE */ + XK_Ucircumflex: 0x00db, /* U+00DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX */ + XK_Udiaeresis: 0x00dc, /* U+00DC LATIN CAPITAL LETTER U WITH DIAERESIS */ + XK_Yacute: 0x00dd, /* U+00DD LATIN CAPITAL LETTER Y WITH ACUTE */ + XK_THORN: 0x00de, /* U+00DE LATIN CAPITAL LETTER THORN */ + XK_Thorn: 0x00de, /* deprecated */ + XK_ssharp: 0x00df, /* U+00DF LATIN SMALL LETTER SHARP S */ + XK_agrave: 0x00e0, /* U+00E0 LATIN SMALL LETTER A WITH GRAVE */ + XK_aacute: 0x00e1, /* U+00E1 LATIN SMALL LETTER A WITH ACUTE */ + XK_acircumflex: 0x00e2, /* U+00E2 LATIN SMALL LETTER A WITH CIRCUMFLEX */ + XK_atilde: 0x00e3, /* U+00E3 LATIN SMALL LETTER A WITH TILDE */ + XK_adiaeresis: 0x00e4, /* U+00E4 LATIN SMALL LETTER A WITH DIAERESIS */ + XK_aring: 0x00e5, /* U+00E5 LATIN SMALL LETTER A WITH RING ABOVE */ + XK_ae: 0x00e6, /* U+00E6 LATIN SMALL LETTER AE */ + XK_ccedilla: 0x00e7, /* U+00E7 LATIN SMALL LETTER C WITH CEDILLA */ + XK_egrave: 0x00e8, /* U+00E8 LATIN SMALL LETTER E WITH GRAVE */ + XK_eacute: 0x00e9, /* U+00E9 LATIN SMALL LETTER E WITH ACUTE */ + XK_ecircumflex: 0x00ea, /* U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX */ + XK_ediaeresis: 0x00eb, /* U+00EB LATIN SMALL LETTER E WITH DIAERESIS */ + XK_igrave: 0x00ec, /* U+00EC LATIN SMALL LETTER I WITH GRAVE */ + XK_iacute: 0x00ed, /* U+00ED LATIN SMALL LETTER I WITH ACUTE */ + XK_icircumflex: 0x00ee, /* U+00EE LATIN SMALL LETTER I WITH CIRCUMFLEX */ + XK_idiaeresis: 0x00ef, /* U+00EF LATIN SMALL LETTER I WITH DIAERESIS */ + XK_eth: 0x00f0, /* U+00F0 LATIN SMALL LETTER ETH */ + XK_ntilde: 0x00f1, /* U+00F1 LATIN SMALL LETTER N WITH TILDE */ + XK_ograve: 0x00f2, /* U+00F2 LATIN SMALL LETTER O WITH GRAVE */ + XK_oacute: 0x00f3, /* U+00F3 LATIN SMALL LETTER O WITH ACUTE */ + XK_ocircumflex: 0x00f4, /* U+00F4 LATIN SMALL LETTER O WITH CIRCUMFLEX */ + XK_otilde: 0x00f5, /* U+00F5 LATIN SMALL LETTER O WITH TILDE */ + XK_odiaeresis: 0x00f6, /* U+00F6 LATIN SMALL LETTER O WITH DIAERESIS */ + XK_division: 0x00f7, /* U+00F7 DIVISION SIGN */ + XK_oslash: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ + XK_ooblique: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ + XK_ugrave: 0x00f9, /* U+00F9 LATIN SMALL LETTER U WITH GRAVE */ + XK_uacute: 0x00fa, /* U+00FA LATIN SMALL LETTER U WITH ACUTE */ + XK_ucircumflex: 0x00fb, /* U+00FB LATIN SMALL LETTER U WITH CIRCUMFLEX */ + XK_udiaeresis: 0x00fc, /* U+00FC LATIN SMALL LETTER U WITH DIAERESIS */ + XK_yacute: 0x00fd, /* U+00FD LATIN SMALL LETTER Y WITH ACUTE */ + XK_thorn: 0x00fe, /* U+00FE LATIN SMALL LETTER THORN */ + XK_ydiaeresis: 0x00ff, /* U+00FF LATIN SMALL LETTER Y WITH DIAERESIS */ + + /* + * Korean + * Byte 3 = 0x0e + */ + + XK_Hangul: 0xff31, /* Hangul start/stop(toggle) */ + XK_Hangul_Hanja: 0xff34, /* Start Hangul->Hanja Conversion */ + XK_Hangul_Jeonja: 0xff38, /* Jeonja mode */ + + /* + * XFree86 vendor specific keysyms. + * + * The XFree86 keysym range is 0x10080001 - 0x1008FFFF. + */ + + XF86XK_ModeLock: 0x1008FF01, + XF86XK_MonBrightnessUp: 0x1008FF02, + XF86XK_MonBrightnessDown: 0x1008FF03, + XF86XK_KbdLightOnOff: 0x1008FF04, + XF86XK_KbdBrightnessUp: 0x1008FF05, + XF86XK_KbdBrightnessDown: 0x1008FF06, + XF86XK_Standby: 0x1008FF10, + XF86XK_AudioLowerVolume: 0x1008FF11, + XF86XK_AudioMute: 0x1008FF12, + XF86XK_AudioRaiseVolume: 0x1008FF13, + XF86XK_AudioPlay: 0x1008FF14, + XF86XK_AudioStop: 0x1008FF15, + XF86XK_AudioPrev: 0x1008FF16, + XF86XK_AudioNext: 0x1008FF17, + XF86XK_HomePage: 0x1008FF18, + XF86XK_Mail: 0x1008FF19, + XF86XK_Start: 0x1008FF1A, + XF86XK_Search: 0x1008FF1B, + XF86XK_AudioRecord: 0x1008FF1C, + XF86XK_Calculator: 0x1008FF1D, + XF86XK_Memo: 0x1008FF1E, + XF86XK_ToDoList: 0x1008FF1F, + XF86XK_Calendar: 0x1008FF20, + XF86XK_PowerDown: 0x1008FF21, + XF86XK_ContrastAdjust: 0x1008FF22, + XF86XK_RockerUp: 0x1008FF23, + XF86XK_RockerDown: 0x1008FF24, + XF86XK_RockerEnter: 0x1008FF25, + XF86XK_Back: 0x1008FF26, + XF86XK_Forward: 0x1008FF27, + XF86XK_Stop: 0x1008FF28, + XF86XK_Refresh: 0x1008FF29, + XF86XK_PowerOff: 0x1008FF2A, + XF86XK_WakeUp: 0x1008FF2B, + XF86XK_Eject: 0x1008FF2C, + XF86XK_ScreenSaver: 0x1008FF2D, + XF86XK_WWW: 0x1008FF2E, + XF86XK_Sleep: 0x1008FF2F, + XF86XK_Favorites: 0x1008FF30, + XF86XK_AudioPause: 0x1008FF31, + XF86XK_AudioMedia: 0x1008FF32, + XF86XK_MyComputer: 0x1008FF33, + XF86XK_VendorHome: 0x1008FF34, + XF86XK_LightBulb: 0x1008FF35, + XF86XK_Shop: 0x1008FF36, + XF86XK_History: 0x1008FF37, + XF86XK_OpenURL: 0x1008FF38, + XF86XK_AddFavorite: 0x1008FF39, + XF86XK_HotLinks: 0x1008FF3A, + XF86XK_BrightnessAdjust: 0x1008FF3B, + XF86XK_Finance: 0x1008FF3C, + XF86XK_Community: 0x1008FF3D, + XF86XK_AudioRewind: 0x1008FF3E, + XF86XK_BackForward: 0x1008FF3F, + XF86XK_Launch0: 0x1008FF40, + XF86XK_Launch1: 0x1008FF41, + XF86XK_Launch2: 0x1008FF42, + XF86XK_Launch3: 0x1008FF43, + XF86XK_Launch4: 0x1008FF44, + XF86XK_Launch5: 0x1008FF45, + XF86XK_Launch6: 0x1008FF46, + XF86XK_Launch7: 0x1008FF47, + XF86XK_Launch8: 0x1008FF48, + XF86XK_Launch9: 0x1008FF49, + XF86XK_LaunchA: 0x1008FF4A, + XF86XK_LaunchB: 0x1008FF4B, + XF86XK_LaunchC: 0x1008FF4C, + XF86XK_LaunchD: 0x1008FF4D, + XF86XK_LaunchE: 0x1008FF4E, + XF86XK_LaunchF: 0x1008FF4F, + XF86XK_ApplicationLeft: 0x1008FF50, + XF86XK_ApplicationRight: 0x1008FF51, + XF86XK_Book: 0x1008FF52, + XF86XK_CD: 0x1008FF53, + XF86XK_Calculater: 0x1008FF54, + XF86XK_Clear: 0x1008FF55, + XF86XK_Close: 0x1008FF56, + XF86XK_Copy: 0x1008FF57, + XF86XK_Cut: 0x1008FF58, + XF86XK_Display: 0x1008FF59, + XF86XK_DOS: 0x1008FF5A, + XF86XK_Documents: 0x1008FF5B, + XF86XK_Excel: 0x1008FF5C, + XF86XK_Explorer: 0x1008FF5D, + XF86XK_Game: 0x1008FF5E, + XF86XK_Go: 0x1008FF5F, + XF86XK_iTouch: 0x1008FF60, + XF86XK_LogOff: 0x1008FF61, + XF86XK_Market: 0x1008FF62, + XF86XK_Meeting: 0x1008FF63, + XF86XK_MenuKB: 0x1008FF65, + XF86XK_MenuPB: 0x1008FF66, + XF86XK_MySites: 0x1008FF67, + XF86XK_New: 0x1008FF68, + XF86XK_News: 0x1008FF69, + XF86XK_OfficeHome: 0x1008FF6A, + XF86XK_Open: 0x1008FF6B, + XF86XK_Option: 0x1008FF6C, + XF86XK_Paste: 0x1008FF6D, + XF86XK_Phone: 0x1008FF6E, + XF86XK_Q: 0x1008FF70, + XF86XK_Reply: 0x1008FF72, + XF86XK_Reload: 0x1008FF73, + XF86XK_RotateWindows: 0x1008FF74, + XF86XK_RotationPB: 0x1008FF75, + XF86XK_RotationKB: 0x1008FF76, + XF86XK_Save: 0x1008FF77, + XF86XK_ScrollUp: 0x1008FF78, + XF86XK_ScrollDown: 0x1008FF79, + XF86XK_ScrollClick: 0x1008FF7A, + XF86XK_Send: 0x1008FF7B, + XF86XK_Spell: 0x1008FF7C, + XF86XK_SplitScreen: 0x1008FF7D, + XF86XK_Support: 0x1008FF7E, + XF86XK_TaskPane: 0x1008FF7F, + XF86XK_Terminal: 0x1008FF80, + XF86XK_Tools: 0x1008FF81, + XF86XK_Travel: 0x1008FF82, + XF86XK_UserPB: 0x1008FF84, + XF86XK_User1KB: 0x1008FF85, + XF86XK_User2KB: 0x1008FF86, + XF86XK_Video: 0x1008FF87, + XF86XK_WheelButton: 0x1008FF88, + XF86XK_Word: 0x1008FF89, + XF86XK_Xfer: 0x1008FF8A, + XF86XK_ZoomIn: 0x1008FF8B, + XF86XK_ZoomOut: 0x1008FF8C, + XF86XK_Away: 0x1008FF8D, + XF86XK_Messenger: 0x1008FF8E, + XF86XK_WebCam: 0x1008FF8F, + XF86XK_MailForward: 0x1008FF90, + XF86XK_Pictures: 0x1008FF91, + XF86XK_Music: 0x1008FF92, + XF86XK_Battery: 0x1008FF93, + XF86XK_Bluetooth: 0x1008FF94, + XF86XK_WLAN: 0x1008FF95, + XF86XK_UWB: 0x1008FF96, + XF86XK_AudioForward: 0x1008FF97, + XF86XK_AudioRepeat: 0x1008FF98, + XF86XK_AudioRandomPlay: 0x1008FF99, + XF86XK_Subtitle: 0x1008FF9A, + XF86XK_AudioCycleTrack: 0x1008FF9B, + XF86XK_CycleAngle: 0x1008FF9C, + XF86XK_FrameBack: 0x1008FF9D, + XF86XK_FrameForward: 0x1008FF9E, + XF86XK_Time: 0x1008FF9F, + XF86XK_Select: 0x1008FFA0, + XF86XK_View: 0x1008FFA1, + XF86XK_TopMenu: 0x1008FFA2, + XF86XK_Red: 0x1008FFA3, + XF86XK_Green: 0x1008FFA4, + XF86XK_Yellow: 0x1008FFA5, + XF86XK_Blue: 0x1008FFA6, + XF86XK_Suspend: 0x1008FFA7, + XF86XK_Hibernate: 0x1008FFA8, + XF86XK_TouchpadToggle: 0x1008FFA9, + XF86XK_TouchpadOn: 0x1008FFB0, + XF86XK_TouchpadOff: 0x1008FFB1, + XF86XK_AudioMicMute: 0x1008FFB2, + XF86XK_Switch_VT_1: 0x1008FE01, + XF86XK_Switch_VT_2: 0x1008FE02, + XF86XK_Switch_VT_3: 0x1008FE03, + XF86XK_Switch_VT_4: 0x1008FE04, + XF86XK_Switch_VT_5: 0x1008FE05, + XF86XK_Switch_VT_6: 0x1008FE06, + XF86XK_Switch_VT_7: 0x1008FE07, + XF86XK_Switch_VT_8: 0x1008FE08, + XF86XK_Switch_VT_9: 0x1008FE09, + XF86XK_Switch_VT_10: 0x1008FE0A, + XF86XK_Switch_VT_11: 0x1008FE0B, + XF86XK_Switch_VT_12: 0x1008FE0C, + XF86XK_Ungrab: 0x1008FE20, + XF86XK_ClearGrab: 0x1008FE21, + XF86XK_Next_VMode: 0x1008FE22, + XF86XK_Prev_VMode: 0x1008FE23, + XF86XK_LogWindowTree: 0x1008FE24, + XF86XK_LogGrabInfo: 0x1008FE25, +}; diff --git a/web/public/cloud/vendor/novnc/core/input/keysymdef.js b/web/public/cloud/vendor/novnc/core/input/keysymdef.js new file mode 100644 index 00000000..951cacab --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/keysymdef.js @@ -0,0 +1,688 @@ +/* + * Mapping from Unicode codepoints to X11/RFB keysyms + * + * This file was automatically generated from keysymdef.h + * DO NOT EDIT! + */ + +/* Functions at the bottom */ + +const codepoints = { + 0x0100: 0x03c0, // XK_Amacron + 0x0101: 0x03e0, // XK_amacron + 0x0102: 0x01c3, // XK_Abreve + 0x0103: 0x01e3, // XK_abreve + 0x0104: 0x01a1, // XK_Aogonek + 0x0105: 0x01b1, // XK_aogonek + 0x0106: 0x01c6, // XK_Cacute + 0x0107: 0x01e6, // XK_cacute + 0x0108: 0x02c6, // XK_Ccircumflex + 0x0109: 0x02e6, // XK_ccircumflex + 0x010a: 0x02c5, // XK_Cabovedot + 0x010b: 0x02e5, // XK_cabovedot + 0x010c: 0x01c8, // XK_Ccaron + 0x010d: 0x01e8, // XK_ccaron + 0x010e: 0x01cf, // XK_Dcaron + 0x010f: 0x01ef, // XK_dcaron + 0x0110: 0x01d0, // XK_Dstroke + 0x0111: 0x01f0, // XK_dstroke + 0x0112: 0x03aa, // XK_Emacron + 0x0113: 0x03ba, // XK_emacron + 0x0116: 0x03cc, // XK_Eabovedot + 0x0117: 0x03ec, // XK_eabovedot + 0x0118: 0x01ca, // XK_Eogonek + 0x0119: 0x01ea, // XK_eogonek + 0x011a: 0x01cc, // XK_Ecaron + 0x011b: 0x01ec, // XK_ecaron + 0x011c: 0x02d8, // XK_Gcircumflex + 0x011d: 0x02f8, // XK_gcircumflex + 0x011e: 0x02ab, // XK_Gbreve + 0x011f: 0x02bb, // XK_gbreve + 0x0120: 0x02d5, // XK_Gabovedot + 0x0121: 0x02f5, // XK_gabovedot + 0x0122: 0x03ab, // XK_Gcedilla + 0x0123: 0x03bb, // XK_gcedilla + 0x0124: 0x02a6, // XK_Hcircumflex + 0x0125: 0x02b6, // XK_hcircumflex + 0x0126: 0x02a1, // XK_Hstroke + 0x0127: 0x02b1, // XK_hstroke + 0x0128: 0x03a5, // XK_Itilde + 0x0129: 0x03b5, // XK_itilde + 0x012a: 0x03cf, // XK_Imacron + 0x012b: 0x03ef, // XK_imacron + 0x012e: 0x03c7, // XK_Iogonek + 0x012f: 0x03e7, // XK_iogonek + 0x0130: 0x02a9, // XK_Iabovedot + 0x0131: 0x02b9, // XK_idotless + 0x0134: 0x02ac, // XK_Jcircumflex + 0x0135: 0x02bc, // XK_jcircumflex + 0x0136: 0x03d3, // XK_Kcedilla + 0x0137: 0x03f3, // XK_kcedilla + 0x0138: 0x03a2, // XK_kra + 0x0139: 0x01c5, // XK_Lacute + 0x013a: 0x01e5, // XK_lacute + 0x013b: 0x03a6, // XK_Lcedilla + 0x013c: 0x03b6, // XK_lcedilla + 0x013d: 0x01a5, // XK_Lcaron + 0x013e: 0x01b5, // XK_lcaron + 0x0141: 0x01a3, // XK_Lstroke + 0x0142: 0x01b3, // XK_lstroke + 0x0143: 0x01d1, // XK_Nacute + 0x0144: 0x01f1, // XK_nacute + 0x0145: 0x03d1, // XK_Ncedilla + 0x0146: 0x03f1, // XK_ncedilla + 0x0147: 0x01d2, // XK_Ncaron + 0x0148: 0x01f2, // XK_ncaron + 0x014a: 0x03bd, // XK_ENG + 0x014b: 0x03bf, // XK_eng + 0x014c: 0x03d2, // XK_Omacron + 0x014d: 0x03f2, // XK_omacron + 0x0150: 0x01d5, // XK_Odoubleacute + 0x0151: 0x01f5, // XK_odoubleacute + 0x0152: 0x13bc, // XK_OE + 0x0153: 0x13bd, // XK_oe + 0x0154: 0x01c0, // XK_Racute + 0x0155: 0x01e0, // XK_racute + 0x0156: 0x03a3, // XK_Rcedilla + 0x0157: 0x03b3, // XK_rcedilla + 0x0158: 0x01d8, // XK_Rcaron + 0x0159: 0x01f8, // XK_rcaron + 0x015a: 0x01a6, // XK_Sacute + 0x015b: 0x01b6, // XK_sacute + 0x015c: 0x02de, // XK_Scircumflex + 0x015d: 0x02fe, // XK_scircumflex + 0x015e: 0x01aa, // XK_Scedilla + 0x015f: 0x01ba, // XK_scedilla + 0x0160: 0x01a9, // XK_Scaron + 0x0161: 0x01b9, // XK_scaron + 0x0162: 0x01de, // XK_Tcedilla + 0x0163: 0x01fe, // XK_tcedilla + 0x0164: 0x01ab, // XK_Tcaron + 0x0165: 0x01bb, // XK_tcaron + 0x0166: 0x03ac, // XK_Tslash + 0x0167: 0x03bc, // XK_tslash + 0x0168: 0x03dd, // XK_Utilde + 0x0169: 0x03fd, // XK_utilde + 0x016a: 0x03de, // XK_Umacron + 0x016b: 0x03fe, // XK_umacron + 0x016c: 0x02dd, // XK_Ubreve + 0x016d: 0x02fd, // XK_ubreve + 0x016e: 0x01d9, // XK_Uring + 0x016f: 0x01f9, // XK_uring + 0x0170: 0x01db, // XK_Udoubleacute + 0x0171: 0x01fb, // XK_udoubleacute + 0x0172: 0x03d9, // XK_Uogonek + 0x0173: 0x03f9, // XK_uogonek + 0x0178: 0x13be, // XK_Ydiaeresis + 0x0179: 0x01ac, // XK_Zacute + 0x017a: 0x01bc, // XK_zacute + 0x017b: 0x01af, // XK_Zabovedot + 0x017c: 0x01bf, // XK_zabovedot + 0x017d: 0x01ae, // XK_Zcaron + 0x017e: 0x01be, // XK_zcaron + 0x0192: 0x08f6, // XK_function + 0x01d2: 0x10001d1, // XK_Ocaron + 0x02c7: 0x01b7, // XK_caron + 0x02d8: 0x01a2, // XK_breve + 0x02d9: 0x01ff, // XK_abovedot + 0x02db: 0x01b2, // XK_ogonek + 0x02dd: 0x01bd, // XK_doubleacute + 0x0385: 0x07ae, // XK_Greek_accentdieresis + 0x0386: 0x07a1, // XK_Greek_ALPHAaccent + 0x0388: 0x07a2, // XK_Greek_EPSILONaccent + 0x0389: 0x07a3, // XK_Greek_ETAaccent + 0x038a: 0x07a4, // XK_Greek_IOTAaccent + 0x038c: 0x07a7, // XK_Greek_OMICRONaccent + 0x038e: 0x07a8, // XK_Greek_UPSILONaccent + 0x038f: 0x07ab, // XK_Greek_OMEGAaccent + 0x0390: 0x07b6, // XK_Greek_iotaaccentdieresis + 0x0391: 0x07c1, // XK_Greek_ALPHA + 0x0392: 0x07c2, // XK_Greek_BETA + 0x0393: 0x07c3, // XK_Greek_GAMMA + 0x0394: 0x07c4, // XK_Greek_DELTA + 0x0395: 0x07c5, // XK_Greek_EPSILON + 0x0396: 0x07c6, // XK_Greek_ZETA + 0x0397: 0x07c7, // XK_Greek_ETA + 0x0398: 0x07c8, // XK_Greek_THETA + 0x0399: 0x07c9, // XK_Greek_IOTA + 0x039a: 0x07ca, // XK_Greek_KAPPA + 0x039b: 0x07cb, // XK_Greek_LAMDA + 0x039c: 0x07cc, // XK_Greek_MU + 0x039d: 0x07cd, // XK_Greek_NU + 0x039e: 0x07ce, // XK_Greek_XI + 0x039f: 0x07cf, // XK_Greek_OMICRON + 0x03a0: 0x07d0, // XK_Greek_PI + 0x03a1: 0x07d1, // XK_Greek_RHO + 0x03a3: 0x07d2, // XK_Greek_SIGMA + 0x03a4: 0x07d4, // XK_Greek_TAU + 0x03a5: 0x07d5, // XK_Greek_UPSILON + 0x03a6: 0x07d6, // XK_Greek_PHI + 0x03a7: 0x07d7, // XK_Greek_CHI + 0x03a8: 0x07d8, // XK_Greek_PSI + 0x03a9: 0x07d9, // XK_Greek_OMEGA + 0x03aa: 0x07a5, // XK_Greek_IOTAdieresis + 0x03ab: 0x07a9, // XK_Greek_UPSILONdieresis + 0x03ac: 0x07b1, // XK_Greek_alphaaccent + 0x03ad: 0x07b2, // XK_Greek_epsilonaccent + 0x03ae: 0x07b3, // XK_Greek_etaaccent + 0x03af: 0x07b4, // XK_Greek_iotaaccent + 0x03b0: 0x07ba, // XK_Greek_upsilonaccentdieresis + 0x03b1: 0x07e1, // XK_Greek_alpha + 0x03b2: 0x07e2, // XK_Greek_beta + 0x03b3: 0x07e3, // XK_Greek_gamma + 0x03b4: 0x07e4, // XK_Greek_delta + 0x03b5: 0x07e5, // XK_Greek_epsilon + 0x03b6: 0x07e6, // XK_Greek_zeta + 0x03b7: 0x07e7, // XK_Greek_eta + 0x03b8: 0x07e8, // XK_Greek_theta + 0x03b9: 0x07e9, // XK_Greek_iota + 0x03ba: 0x07ea, // XK_Greek_kappa + 0x03bb: 0x07eb, // XK_Greek_lamda + 0x03bc: 0x07ec, // XK_Greek_mu + 0x03bd: 0x07ed, // XK_Greek_nu + 0x03be: 0x07ee, // XK_Greek_xi + 0x03bf: 0x07ef, // XK_Greek_omicron + 0x03c0: 0x07f0, // XK_Greek_pi + 0x03c1: 0x07f1, // XK_Greek_rho + 0x03c2: 0x07f3, // XK_Greek_finalsmallsigma + 0x03c3: 0x07f2, // XK_Greek_sigma + 0x03c4: 0x07f4, // XK_Greek_tau + 0x03c5: 0x07f5, // XK_Greek_upsilon + 0x03c6: 0x07f6, // XK_Greek_phi + 0x03c7: 0x07f7, // XK_Greek_chi + 0x03c8: 0x07f8, // XK_Greek_psi + 0x03c9: 0x07f9, // XK_Greek_omega + 0x03ca: 0x07b5, // XK_Greek_iotadieresis + 0x03cb: 0x07b9, // XK_Greek_upsilondieresis + 0x03cc: 0x07b7, // XK_Greek_omicronaccent + 0x03cd: 0x07b8, // XK_Greek_upsilonaccent + 0x03ce: 0x07bb, // XK_Greek_omegaaccent + 0x0401: 0x06b3, // XK_Cyrillic_IO + 0x0402: 0x06b1, // XK_Serbian_DJE + 0x0403: 0x06b2, // XK_Macedonia_GJE + 0x0404: 0x06b4, // XK_Ukrainian_IE + 0x0405: 0x06b5, // XK_Macedonia_DSE + 0x0406: 0x06b6, // XK_Ukrainian_I + 0x0407: 0x06b7, // XK_Ukrainian_YI + 0x0408: 0x06b8, // XK_Cyrillic_JE + 0x0409: 0x06b9, // XK_Cyrillic_LJE + 0x040a: 0x06ba, // XK_Cyrillic_NJE + 0x040b: 0x06bb, // XK_Serbian_TSHE + 0x040c: 0x06bc, // XK_Macedonia_KJE + 0x040e: 0x06be, // XK_Byelorussian_SHORTU + 0x040f: 0x06bf, // XK_Cyrillic_DZHE + 0x0410: 0x06e1, // XK_Cyrillic_A + 0x0411: 0x06e2, // XK_Cyrillic_BE + 0x0412: 0x06f7, // XK_Cyrillic_VE + 0x0413: 0x06e7, // XK_Cyrillic_GHE + 0x0414: 0x06e4, // XK_Cyrillic_DE + 0x0415: 0x06e5, // XK_Cyrillic_IE + 0x0416: 0x06f6, // XK_Cyrillic_ZHE + 0x0417: 0x06fa, // XK_Cyrillic_ZE + 0x0418: 0x06e9, // XK_Cyrillic_I + 0x0419: 0x06ea, // XK_Cyrillic_SHORTI + 0x041a: 0x06eb, // XK_Cyrillic_KA + 0x041b: 0x06ec, // XK_Cyrillic_EL + 0x041c: 0x06ed, // XK_Cyrillic_EM + 0x041d: 0x06ee, // XK_Cyrillic_EN + 0x041e: 0x06ef, // XK_Cyrillic_O + 0x041f: 0x06f0, // XK_Cyrillic_PE + 0x0420: 0x06f2, // XK_Cyrillic_ER + 0x0421: 0x06f3, // XK_Cyrillic_ES + 0x0422: 0x06f4, // XK_Cyrillic_TE + 0x0423: 0x06f5, // XK_Cyrillic_U + 0x0424: 0x06e6, // XK_Cyrillic_EF + 0x0425: 0x06e8, // XK_Cyrillic_HA + 0x0426: 0x06e3, // XK_Cyrillic_TSE + 0x0427: 0x06fe, // XK_Cyrillic_CHE + 0x0428: 0x06fb, // XK_Cyrillic_SHA + 0x0429: 0x06fd, // XK_Cyrillic_SHCHA + 0x042a: 0x06ff, // XK_Cyrillic_HARDSIGN + 0x042b: 0x06f9, // XK_Cyrillic_YERU + 0x042c: 0x06f8, // XK_Cyrillic_SOFTSIGN + 0x042d: 0x06fc, // XK_Cyrillic_E + 0x042e: 0x06e0, // XK_Cyrillic_YU + 0x042f: 0x06f1, // XK_Cyrillic_YA + 0x0430: 0x06c1, // XK_Cyrillic_a + 0x0431: 0x06c2, // XK_Cyrillic_be + 0x0432: 0x06d7, // XK_Cyrillic_ve + 0x0433: 0x06c7, // XK_Cyrillic_ghe + 0x0434: 0x06c4, // XK_Cyrillic_de + 0x0435: 0x06c5, // XK_Cyrillic_ie + 0x0436: 0x06d6, // XK_Cyrillic_zhe + 0x0437: 0x06da, // XK_Cyrillic_ze + 0x0438: 0x06c9, // XK_Cyrillic_i + 0x0439: 0x06ca, // XK_Cyrillic_shorti + 0x043a: 0x06cb, // XK_Cyrillic_ka + 0x043b: 0x06cc, // XK_Cyrillic_el + 0x043c: 0x06cd, // XK_Cyrillic_em + 0x043d: 0x06ce, // XK_Cyrillic_en + 0x043e: 0x06cf, // XK_Cyrillic_o + 0x043f: 0x06d0, // XK_Cyrillic_pe + 0x0440: 0x06d2, // XK_Cyrillic_er + 0x0441: 0x06d3, // XK_Cyrillic_es + 0x0442: 0x06d4, // XK_Cyrillic_te + 0x0443: 0x06d5, // XK_Cyrillic_u + 0x0444: 0x06c6, // XK_Cyrillic_ef + 0x0445: 0x06c8, // XK_Cyrillic_ha + 0x0446: 0x06c3, // XK_Cyrillic_tse + 0x0447: 0x06de, // XK_Cyrillic_che + 0x0448: 0x06db, // XK_Cyrillic_sha + 0x0449: 0x06dd, // XK_Cyrillic_shcha + 0x044a: 0x06df, // XK_Cyrillic_hardsign + 0x044b: 0x06d9, // XK_Cyrillic_yeru + 0x044c: 0x06d8, // XK_Cyrillic_softsign + 0x044d: 0x06dc, // XK_Cyrillic_e + 0x044e: 0x06c0, // XK_Cyrillic_yu + 0x044f: 0x06d1, // XK_Cyrillic_ya + 0x0451: 0x06a3, // XK_Cyrillic_io + 0x0452: 0x06a1, // XK_Serbian_dje + 0x0453: 0x06a2, // XK_Macedonia_gje + 0x0454: 0x06a4, // XK_Ukrainian_ie + 0x0455: 0x06a5, // XK_Macedonia_dse + 0x0456: 0x06a6, // XK_Ukrainian_i + 0x0457: 0x06a7, // XK_Ukrainian_yi + 0x0458: 0x06a8, // XK_Cyrillic_je + 0x0459: 0x06a9, // XK_Cyrillic_lje + 0x045a: 0x06aa, // XK_Cyrillic_nje + 0x045b: 0x06ab, // XK_Serbian_tshe + 0x045c: 0x06ac, // XK_Macedonia_kje + 0x045e: 0x06ae, // XK_Byelorussian_shortu + 0x045f: 0x06af, // XK_Cyrillic_dzhe + 0x0490: 0x06bd, // XK_Ukrainian_GHE_WITH_UPTURN + 0x0491: 0x06ad, // XK_Ukrainian_ghe_with_upturn + 0x05d0: 0x0ce0, // XK_hebrew_aleph + 0x05d1: 0x0ce1, // XK_hebrew_bet + 0x05d2: 0x0ce2, // XK_hebrew_gimel + 0x05d3: 0x0ce3, // XK_hebrew_dalet + 0x05d4: 0x0ce4, // XK_hebrew_he + 0x05d5: 0x0ce5, // XK_hebrew_waw + 0x05d6: 0x0ce6, // XK_hebrew_zain + 0x05d7: 0x0ce7, // XK_hebrew_chet + 0x05d8: 0x0ce8, // XK_hebrew_tet + 0x05d9: 0x0ce9, // XK_hebrew_yod + 0x05da: 0x0cea, // XK_hebrew_finalkaph + 0x05db: 0x0ceb, // XK_hebrew_kaph + 0x05dc: 0x0cec, // XK_hebrew_lamed + 0x05dd: 0x0ced, // XK_hebrew_finalmem + 0x05de: 0x0cee, // XK_hebrew_mem + 0x05df: 0x0cef, // XK_hebrew_finalnun + 0x05e0: 0x0cf0, // XK_hebrew_nun + 0x05e1: 0x0cf1, // XK_hebrew_samech + 0x05e2: 0x0cf2, // XK_hebrew_ayin + 0x05e3: 0x0cf3, // XK_hebrew_finalpe + 0x05e4: 0x0cf4, // XK_hebrew_pe + 0x05e5: 0x0cf5, // XK_hebrew_finalzade + 0x05e6: 0x0cf6, // XK_hebrew_zade + 0x05e7: 0x0cf7, // XK_hebrew_qoph + 0x05e8: 0x0cf8, // XK_hebrew_resh + 0x05e9: 0x0cf9, // XK_hebrew_shin + 0x05ea: 0x0cfa, // XK_hebrew_taw + 0x060c: 0x05ac, // XK_Arabic_comma + 0x061b: 0x05bb, // XK_Arabic_semicolon + 0x061f: 0x05bf, // XK_Arabic_question_mark + 0x0621: 0x05c1, // XK_Arabic_hamza + 0x0622: 0x05c2, // XK_Arabic_maddaonalef + 0x0623: 0x05c3, // XK_Arabic_hamzaonalef + 0x0624: 0x05c4, // XK_Arabic_hamzaonwaw + 0x0625: 0x05c5, // XK_Arabic_hamzaunderalef + 0x0626: 0x05c6, // XK_Arabic_hamzaonyeh + 0x0627: 0x05c7, // XK_Arabic_alef + 0x0628: 0x05c8, // XK_Arabic_beh + 0x0629: 0x05c9, // XK_Arabic_tehmarbuta + 0x062a: 0x05ca, // XK_Arabic_teh + 0x062b: 0x05cb, // XK_Arabic_theh + 0x062c: 0x05cc, // XK_Arabic_jeem + 0x062d: 0x05cd, // XK_Arabic_hah + 0x062e: 0x05ce, // XK_Arabic_khah + 0x062f: 0x05cf, // XK_Arabic_dal + 0x0630: 0x05d0, // XK_Arabic_thal + 0x0631: 0x05d1, // XK_Arabic_ra + 0x0632: 0x05d2, // XK_Arabic_zain + 0x0633: 0x05d3, // XK_Arabic_seen + 0x0634: 0x05d4, // XK_Arabic_sheen + 0x0635: 0x05d5, // XK_Arabic_sad + 0x0636: 0x05d6, // XK_Arabic_dad + 0x0637: 0x05d7, // XK_Arabic_tah + 0x0638: 0x05d8, // XK_Arabic_zah + 0x0639: 0x05d9, // XK_Arabic_ain + 0x063a: 0x05da, // XK_Arabic_ghain + 0x0640: 0x05e0, // XK_Arabic_tatweel + 0x0641: 0x05e1, // XK_Arabic_feh + 0x0642: 0x05e2, // XK_Arabic_qaf + 0x0643: 0x05e3, // XK_Arabic_kaf + 0x0644: 0x05e4, // XK_Arabic_lam + 0x0645: 0x05e5, // XK_Arabic_meem + 0x0646: 0x05e6, // XK_Arabic_noon + 0x0647: 0x05e7, // XK_Arabic_ha + 0x0648: 0x05e8, // XK_Arabic_waw + 0x0649: 0x05e9, // XK_Arabic_alefmaksura + 0x064a: 0x05ea, // XK_Arabic_yeh + 0x064b: 0x05eb, // XK_Arabic_fathatan + 0x064c: 0x05ec, // XK_Arabic_dammatan + 0x064d: 0x05ed, // XK_Arabic_kasratan + 0x064e: 0x05ee, // XK_Arabic_fatha + 0x064f: 0x05ef, // XK_Arabic_damma + 0x0650: 0x05f0, // XK_Arabic_kasra + 0x0651: 0x05f1, // XK_Arabic_shadda + 0x0652: 0x05f2, // XK_Arabic_sukun + 0x0e01: 0x0da1, // XK_Thai_kokai + 0x0e02: 0x0da2, // XK_Thai_khokhai + 0x0e03: 0x0da3, // XK_Thai_khokhuat + 0x0e04: 0x0da4, // XK_Thai_khokhwai + 0x0e05: 0x0da5, // XK_Thai_khokhon + 0x0e06: 0x0da6, // XK_Thai_khorakhang + 0x0e07: 0x0da7, // XK_Thai_ngongu + 0x0e08: 0x0da8, // XK_Thai_chochan + 0x0e09: 0x0da9, // XK_Thai_choching + 0x0e0a: 0x0daa, // XK_Thai_chochang + 0x0e0b: 0x0dab, // XK_Thai_soso + 0x0e0c: 0x0dac, // XK_Thai_chochoe + 0x0e0d: 0x0dad, // XK_Thai_yoying + 0x0e0e: 0x0dae, // XK_Thai_dochada + 0x0e0f: 0x0daf, // XK_Thai_topatak + 0x0e10: 0x0db0, // XK_Thai_thothan + 0x0e11: 0x0db1, // XK_Thai_thonangmontho + 0x0e12: 0x0db2, // XK_Thai_thophuthao + 0x0e13: 0x0db3, // XK_Thai_nonen + 0x0e14: 0x0db4, // XK_Thai_dodek + 0x0e15: 0x0db5, // XK_Thai_totao + 0x0e16: 0x0db6, // XK_Thai_thothung + 0x0e17: 0x0db7, // XK_Thai_thothahan + 0x0e18: 0x0db8, // XK_Thai_thothong + 0x0e19: 0x0db9, // XK_Thai_nonu + 0x0e1a: 0x0dba, // XK_Thai_bobaimai + 0x0e1b: 0x0dbb, // XK_Thai_popla + 0x0e1c: 0x0dbc, // XK_Thai_phophung + 0x0e1d: 0x0dbd, // XK_Thai_fofa + 0x0e1e: 0x0dbe, // XK_Thai_phophan + 0x0e1f: 0x0dbf, // XK_Thai_fofan + 0x0e20: 0x0dc0, // XK_Thai_phosamphao + 0x0e21: 0x0dc1, // XK_Thai_moma + 0x0e22: 0x0dc2, // XK_Thai_yoyak + 0x0e23: 0x0dc3, // XK_Thai_rorua + 0x0e24: 0x0dc4, // XK_Thai_ru + 0x0e25: 0x0dc5, // XK_Thai_loling + 0x0e26: 0x0dc6, // XK_Thai_lu + 0x0e27: 0x0dc7, // XK_Thai_wowaen + 0x0e28: 0x0dc8, // XK_Thai_sosala + 0x0e29: 0x0dc9, // XK_Thai_sorusi + 0x0e2a: 0x0dca, // XK_Thai_sosua + 0x0e2b: 0x0dcb, // XK_Thai_hohip + 0x0e2c: 0x0dcc, // XK_Thai_lochula + 0x0e2d: 0x0dcd, // XK_Thai_oang + 0x0e2e: 0x0dce, // XK_Thai_honokhuk + 0x0e2f: 0x0dcf, // XK_Thai_paiyannoi + 0x0e30: 0x0dd0, // XK_Thai_saraa + 0x0e31: 0x0dd1, // XK_Thai_maihanakat + 0x0e32: 0x0dd2, // XK_Thai_saraaa + 0x0e33: 0x0dd3, // XK_Thai_saraam + 0x0e34: 0x0dd4, // XK_Thai_sarai + 0x0e35: 0x0dd5, // XK_Thai_saraii + 0x0e36: 0x0dd6, // XK_Thai_saraue + 0x0e37: 0x0dd7, // XK_Thai_sarauee + 0x0e38: 0x0dd8, // XK_Thai_sarau + 0x0e39: 0x0dd9, // XK_Thai_sarauu + 0x0e3a: 0x0dda, // XK_Thai_phinthu + 0x0e3f: 0x0ddf, // XK_Thai_baht + 0x0e40: 0x0de0, // XK_Thai_sarae + 0x0e41: 0x0de1, // XK_Thai_saraae + 0x0e42: 0x0de2, // XK_Thai_sarao + 0x0e43: 0x0de3, // XK_Thai_saraaimaimuan + 0x0e44: 0x0de4, // XK_Thai_saraaimaimalai + 0x0e45: 0x0de5, // XK_Thai_lakkhangyao + 0x0e46: 0x0de6, // XK_Thai_maiyamok + 0x0e47: 0x0de7, // XK_Thai_maitaikhu + 0x0e48: 0x0de8, // XK_Thai_maiek + 0x0e49: 0x0de9, // XK_Thai_maitho + 0x0e4a: 0x0dea, // XK_Thai_maitri + 0x0e4b: 0x0deb, // XK_Thai_maichattawa + 0x0e4c: 0x0dec, // XK_Thai_thanthakhat + 0x0e4d: 0x0ded, // XK_Thai_nikhahit + 0x0e50: 0x0df0, // XK_Thai_leksun + 0x0e51: 0x0df1, // XK_Thai_leknung + 0x0e52: 0x0df2, // XK_Thai_leksong + 0x0e53: 0x0df3, // XK_Thai_leksam + 0x0e54: 0x0df4, // XK_Thai_leksi + 0x0e55: 0x0df5, // XK_Thai_lekha + 0x0e56: 0x0df6, // XK_Thai_lekhok + 0x0e57: 0x0df7, // XK_Thai_lekchet + 0x0e58: 0x0df8, // XK_Thai_lekpaet + 0x0e59: 0x0df9, // XK_Thai_lekkao + 0x2002: 0x0aa2, // XK_enspace + 0x2003: 0x0aa1, // XK_emspace + 0x2004: 0x0aa3, // XK_em3space + 0x2005: 0x0aa4, // XK_em4space + 0x2007: 0x0aa5, // XK_digitspace + 0x2008: 0x0aa6, // XK_punctspace + 0x2009: 0x0aa7, // XK_thinspace + 0x200a: 0x0aa8, // XK_hairspace + 0x2012: 0x0abb, // XK_figdash + 0x2013: 0x0aaa, // XK_endash + 0x2014: 0x0aa9, // XK_emdash + 0x2015: 0x07af, // XK_Greek_horizbar + 0x2017: 0x0cdf, // XK_hebrew_doublelowline + 0x2018: 0x0ad0, // XK_leftsinglequotemark + 0x2019: 0x0ad1, // XK_rightsinglequotemark + 0x201a: 0x0afd, // XK_singlelowquotemark + 0x201c: 0x0ad2, // XK_leftdoublequotemark + 0x201d: 0x0ad3, // XK_rightdoublequotemark + 0x201e: 0x0afe, // XK_doublelowquotemark + 0x2020: 0x0af1, // XK_dagger + 0x2021: 0x0af2, // XK_doubledagger + 0x2022: 0x0ae6, // XK_enfilledcircbullet + 0x2025: 0x0aaf, // XK_doubbaselinedot + 0x2026: 0x0aae, // XK_ellipsis + 0x2030: 0x0ad5, // XK_permille + 0x2032: 0x0ad6, // XK_minutes + 0x2033: 0x0ad7, // XK_seconds + 0x2038: 0x0afc, // XK_caret + 0x203e: 0x047e, // XK_overline + 0x20a9: 0x0eff, // XK_Korean_Won + 0x20ac: 0x20ac, // XK_EuroSign + 0x2105: 0x0ab8, // XK_careof + 0x2116: 0x06b0, // XK_numerosign + 0x2117: 0x0afb, // XK_phonographcopyright + 0x211e: 0x0ad4, // XK_prescription + 0x2122: 0x0ac9, // XK_trademark + 0x2153: 0x0ab0, // XK_onethird + 0x2154: 0x0ab1, // XK_twothirds + 0x2155: 0x0ab2, // XK_onefifth + 0x2156: 0x0ab3, // XK_twofifths + 0x2157: 0x0ab4, // XK_threefifths + 0x2158: 0x0ab5, // XK_fourfifths + 0x2159: 0x0ab6, // XK_onesixth + 0x215a: 0x0ab7, // XK_fivesixths + 0x215b: 0x0ac3, // XK_oneeighth + 0x215c: 0x0ac4, // XK_threeeighths + 0x215d: 0x0ac5, // XK_fiveeighths + 0x215e: 0x0ac6, // XK_seveneighths + 0x2190: 0x08fb, // XK_leftarrow + 0x2191: 0x08fc, // XK_uparrow + 0x2192: 0x08fd, // XK_rightarrow + 0x2193: 0x08fe, // XK_downarrow + 0x21d2: 0x08ce, // XK_implies + 0x21d4: 0x08cd, // XK_ifonlyif + 0x2202: 0x08ef, // XK_partialderivative + 0x2207: 0x08c5, // XK_nabla + 0x2218: 0x0bca, // XK_jot + 0x221a: 0x08d6, // XK_radical + 0x221d: 0x08c1, // XK_variation + 0x221e: 0x08c2, // XK_infinity + 0x2227: 0x08de, // XK_logicaland + 0x2228: 0x08df, // XK_logicalor + 0x2229: 0x08dc, // XK_intersection + 0x222a: 0x08dd, // XK_union + 0x222b: 0x08bf, // XK_integral + 0x2234: 0x08c0, // XK_therefore + 0x223c: 0x08c8, // XK_approximate + 0x2243: 0x08c9, // XK_similarequal + 0x2245: 0x1002248, // XK_approxeq + 0x2260: 0x08bd, // XK_notequal + 0x2261: 0x08cf, // XK_identical + 0x2264: 0x08bc, // XK_lessthanequal + 0x2265: 0x08be, // XK_greaterthanequal + 0x2282: 0x08da, // XK_includedin + 0x2283: 0x08db, // XK_includes + 0x22a2: 0x0bfc, // XK_righttack + 0x22a3: 0x0bdc, // XK_lefttack + 0x22a4: 0x0bc2, // XK_downtack + 0x22a5: 0x0bce, // XK_uptack + 0x2308: 0x0bd3, // XK_upstile + 0x230a: 0x0bc4, // XK_downstile + 0x2315: 0x0afa, // XK_telephonerecorder + 0x2320: 0x08a4, // XK_topintegral + 0x2321: 0x08a5, // XK_botintegral + 0x2395: 0x0bcc, // XK_quad + 0x239b: 0x08ab, // XK_topleftparens + 0x239d: 0x08ac, // XK_botleftparens + 0x239e: 0x08ad, // XK_toprightparens + 0x23a0: 0x08ae, // XK_botrightparens + 0x23a1: 0x08a7, // XK_topleftsqbracket + 0x23a3: 0x08a8, // XK_botleftsqbracket + 0x23a4: 0x08a9, // XK_toprightsqbracket + 0x23a6: 0x08aa, // XK_botrightsqbracket + 0x23a8: 0x08af, // XK_leftmiddlecurlybrace + 0x23ac: 0x08b0, // XK_rightmiddlecurlybrace + 0x23b7: 0x08a1, // XK_leftradical + 0x23ba: 0x09ef, // XK_horizlinescan1 + 0x23bb: 0x09f0, // XK_horizlinescan3 + 0x23bc: 0x09f2, // XK_horizlinescan7 + 0x23bd: 0x09f3, // XK_horizlinescan9 + 0x2409: 0x09e2, // XK_ht + 0x240a: 0x09e5, // XK_lf + 0x240b: 0x09e9, // XK_vt + 0x240c: 0x09e3, // XK_ff + 0x240d: 0x09e4, // XK_cr + 0x2423: 0x0aac, // XK_signifblank + 0x2424: 0x09e8, // XK_nl + 0x2500: 0x08a3, // XK_horizconnector + 0x2502: 0x08a6, // XK_vertconnector + 0x250c: 0x08a2, // XK_topleftradical + 0x2510: 0x09eb, // XK_uprightcorner + 0x2514: 0x09ed, // XK_lowleftcorner + 0x2518: 0x09ea, // XK_lowrightcorner + 0x251c: 0x09f4, // XK_leftt + 0x2524: 0x09f5, // XK_rightt + 0x252c: 0x09f7, // XK_topt + 0x2534: 0x09f6, // XK_bott + 0x253c: 0x09ee, // XK_crossinglines + 0x2592: 0x09e1, // XK_checkerboard + 0x25aa: 0x0ae7, // XK_enfilledsqbullet + 0x25ab: 0x0ae1, // XK_enopensquarebullet + 0x25ac: 0x0adb, // XK_filledrectbullet + 0x25ad: 0x0ae2, // XK_openrectbullet + 0x25ae: 0x0adf, // XK_emfilledrect + 0x25af: 0x0acf, // XK_emopenrectangle + 0x25b2: 0x0ae8, // XK_filledtribulletup + 0x25b3: 0x0ae3, // XK_opentribulletup + 0x25b6: 0x0add, // XK_filledrighttribullet + 0x25b7: 0x0acd, // XK_rightopentriangle + 0x25bc: 0x0ae9, // XK_filledtribulletdown + 0x25bd: 0x0ae4, // XK_opentribulletdown + 0x25c0: 0x0adc, // XK_filledlefttribullet + 0x25c1: 0x0acc, // XK_leftopentriangle + 0x25c6: 0x09e0, // XK_soliddiamond + 0x25cb: 0x0ace, // XK_emopencircle + 0x25cf: 0x0ade, // XK_emfilledcircle + 0x25e6: 0x0ae0, // XK_enopencircbullet + 0x2606: 0x0ae5, // XK_openstar + 0x260e: 0x0af9, // XK_telephone + 0x2613: 0x0aca, // XK_signaturemark + 0x261c: 0x0aea, // XK_leftpointer + 0x261e: 0x0aeb, // XK_rightpointer + 0x2640: 0x0af8, // XK_femalesymbol + 0x2642: 0x0af7, // XK_malesymbol + 0x2663: 0x0aec, // XK_club + 0x2665: 0x0aee, // XK_heart + 0x2666: 0x0aed, // XK_diamond + 0x266d: 0x0af6, // XK_musicalflat + 0x266f: 0x0af5, // XK_musicalsharp + 0x2713: 0x0af3, // XK_checkmark + 0x2717: 0x0af4, // XK_ballotcross + 0x271d: 0x0ad9, // XK_latincross + 0x2720: 0x0af0, // XK_maltesecross + 0x27e8: 0x0abc, // XK_leftanglebracket + 0x27e9: 0x0abe, // XK_rightanglebracket + 0x3001: 0x04a4, // XK_kana_comma + 0x3002: 0x04a1, // XK_kana_fullstop + 0x300c: 0x04a2, // XK_kana_openingbracket + 0x300d: 0x04a3, // XK_kana_closingbracket + 0x309b: 0x04de, // XK_voicedsound + 0x309c: 0x04df, // XK_semivoicedsound + 0x30a1: 0x04a7, // XK_kana_a + 0x30a2: 0x04b1, // XK_kana_A + 0x30a3: 0x04a8, // XK_kana_i + 0x30a4: 0x04b2, // XK_kana_I + 0x30a5: 0x04a9, // XK_kana_u + 0x30a6: 0x04b3, // XK_kana_U + 0x30a7: 0x04aa, // XK_kana_e + 0x30a8: 0x04b4, // XK_kana_E + 0x30a9: 0x04ab, // XK_kana_o + 0x30aa: 0x04b5, // XK_kana_O + 0x30ab: 0x04b6, // XK_kana_KA + 0x30ad: 0x04b7, // XK_kana_KI + 0x30af: 0x04b8, // XK_kana_KU + 0x30b1: 0x04b9, // XK_kana_KE + 0x30b3: 0x04ba, // XK_kana_KO + 0x30b5: 0x04bb, // XK_kana_SA + 0x30b7: 0x04bc, // XK_kana_SHI + 0x30b9: 0x04bd, // XK_kana_SU + 0x30bb: 0x04be, // XK_kana_SE + 0x30bd: 0x04bf, // XK_kana_SO + 0x30bf: 0x04c0, // XK_kana_TA + 0x30c1: 0x04c1, // XK_kana_CHI + 0x30c3: 0x04af, // XK_kana_tsu + 0x30c4: 0x04c2, // XK_kana_TSU + 0x30c6: 0x04c3, // XK_kana_TE + 0x30c8: 0x04c4, // XK_kana_TO + 0x30ca: 0x04c5, // XK_kana_NA + 0x30cb: 0x04c6, // XK_kana_NI + 0x30cc: 0x04c7, // XK_kana_NU + 0x30cd: 0x04c8, // XK_kana_NE + 0x30ce: 0x04c9, // XK_kana_NO + 0x30cf: 0x04ca, // XK_kana_HA + 0x30d2: 0x04cb, // XK_kana_HI + 0x30d5: 0x04cc, // XK_kana_FU + 0x30d8: 0x04cd, // XK_kana_HE + 0x30db: 0x04ce, // XK_kana_HO + 0x30de: 0x04cf, // XK_kana_MA + 0x30df: 0x04d0, // XK_kana_MI + 0x30e0: 0x04d1, // XK_kana_MU + 0x30e1: 0x04d2, // XK_kana_ME + 0x30e2: 0x04d3, // XK_kana_MO + 0x30e3: 0x04ac, // XK_kana_ya + 0x30e4: 0x04d4, // XK_kana_YA + 0x30e5: 0x04ad, // XK_kana_yu + 0x30e6: 0x04d5, // XK_kana_YU + 0x30e7: 0x04ae, // XK_kana_yo + 0x30e8: 0x04d6, // XK_kana_YO + 0x30e9: 0x04d7, // XK_kana_RA + 0x30ea: 0x04d8, // XK_kana_RI + 0x30eb: 0x04d9, // XK_kana_RU + 0x30ec: 0x04da, // XK_kana_RE + 0x30ed: 0x04db, // XK_kana_RO + 0x30ef: 0x04dc, // XK_kana_WA + 0x30f2: 0x04a6, // XK_kana_WO + 0x30f3: 0x04dd, // XK_kana_N + 0x30fb: 0x04a5, // XK_kana_conjunctive + 0x30fc: 0x04b0, // XK_prolongedsound +}; + +export default { + lookup(u) { + // Latin-1 is one-to-one mapping + if ((u >= 0x20) && (u <= 0xff)) { + return u; + } + + // Lookup table (fairly random) + const keysym = codepoints[u]; + if (keysym !== undefined) { + return keysym; + } + + // General mapping as final fallback + return 0x01000000 | u; + }, +}; diff --git a/web/public/cloud/vendor/novnc/core/input/util.js b/web/public/cloud/vendor/novnc/core/input/util.js new file mode 100644 index 00000000..36b69817 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/util.js @@ -0,0 +1,191 @@ +import KeyTable from "./keysym.js"; +import keysyms from "./keysymdef.js"; +import vkeys from "./vkeys.js"; +import fixedkeys from "./fixedkeys.js"; +import DOMKeyTable from "./domkeytable.js"; +import * as browser from "../util/browser.js"; + +// Get 'KeyboardEvent.code', handling legacy browsers +export function getKeycode(evt) { + // Are we getting proper key identifiers? + // (unfortunately Firefox and Chrome are crappy here and gives + // us an empty string on some platforms, rather than leaving it + // undefined) + if (evt.code) { + // Mozilla isn't fully in sync with the spec yet + switch (evt.code) { + case 'OSLeft': return 'MetaLeft'; + case 'OSRight': return 'MetaRight'; + } + + return evt.code; + } + + // The de-facto standard is to use Windows Virtual-Key codes + // in the 'keyCode' field for non-printable characters + if (evt.keyCode in vkeys) { + let code = vkeys[evt.keyCode]; + + // macOS has messed up this code for some reason + if (browser.isMac() && (code === 'ContextMenu')) { + code = 'MetaRight'; + } + + // The keyCode doesn't distinguish between left and right + // for the standard modifiers + if (evt.location === 2) { + switch (code) { + case 'ShiftLeft': return 'ShiftRight'; + case 'ControlLeft': return 'ControlRight'; + case 'AltLeft': return 'AltRight'; + } + } + + // Nor a bunch of the numpad keys + if (evt.location === 3) { + switch (code) { + case 'Delete': return 'NumpadDecimal'; + case 'Insert': return 'Numpad0'; + case 'End': return 'Numpad1'; + case 'ArrowDown': return 'Numpad2'; + case 'PageDown': return 'Numpad3'; + case 'ArrowLeft': return 'Numpad4'; + case 'ArrowRight': return 'Numpad6'; + case 'Home': return 'Numpad7'; + case 'ArrowUp': return 'Numpad8'; + case 'PageUp': return 'Numpad9'; + case 'Enter': return 'NumpadEnter'; + } + } + + return code; + } + + return 'Unidentified'; +} + +// Get 'KeyboardEvent.key', handling legacy browsers +export function getKey(evt) { + // Are we getting a proper key value? + if ((evt.key !== undefined) && (evt.key !== 'Unidentified')) { + // Mozilla isn't fully in sync with the spec yet + switch (evt.key) { + case 'OS': return 'Meta'; + case 'LaunchMyComputer': return 'LaunchApplication1'; + case 'LaunchCalculator': return 'LaunchApplication2'; + } + + // iOS leaks some OS names + switch (evt.key) { + case 'UIKeyInputUpArrow': return 'ArrowUp'; + case 'UIKeyInputDownArrow': return 'ArrowDown'; + case 'UIKeyInputLeftArrow': return 'ArrowLeft'; + case 'UIKeyInputRightArrow': return 'ArrowRight'; + case 'UIKeyInputEscape': return 'Escape'; + } + + // Broken behaviour in Chrome + if ((evt.key === '\x00') && (evt.code === 'NumpadDecimal')) { + return 'Delete'; + } + + return evt.key; + } + + // Try to deduce it based on the physical key + const code = getKeycode(evt); + if (code in fixedkeys) { + return fixedkeys[code]; + } + + // If that failed, then see if we have a printable character + if (evt.charCode) { + return String.fromCharCode(evt.charCode); + } + + // At this point we have nothing left to go on + return 'Unidentified'; +} + +// Get the most reliable keysym value we can get from a key event +export function getKeysym(evt) { + const key = getKey(evt); + + if (key === 'Unidentified') { + return null; + } + + // First look up special keys + if (key in DOMKeyTable) { + let location = evt.location; + + // Safari screws up location for the right cmd key + if ((key === 'Meta') && (location === 0)) { + location = 2; + } + + // And for Clear + if ((key === 'Clear') && (location === 3)) { + let code = getKeycode(evt); + if (code === 'NumLock') { + location = 0; + } + } + + if ((location === undefined) || (location > 3)) { + location = 0; + } + + // The original Meta key now gets confused with the Windows key + // https://bugs.chromium.org/p/chromium/issues/detail?id=1020141 + // https://bugzilla.mozilla.org/show_bug.cgi?id=1232918 + if (key === 'Meta') { + let code = getKeycode(evt); + if (code === 'AltLeft') { + return KeyTable.XK_Meta_L; + } else if (code === 'AltRight') { + return KeyTable.XK_Meta_R; + } + } + + // macOS has Clear instead of NumLock, but the remote system is + // probably not macOS, so lying here is probably best... + if (key === 'Clear') { + let code = getKeycode(evt); + if (code === 'NumLock') { + return KeyTable.XK_Num_Lock; + } + } + + // Windows sends alternating symbols for some keys when using a + // Japanese layout. We have no way of synchronising with the IM + // running on the remote system, so we send some combined keysym + // instead and hope for the best. + if (browser.isWindows()) { + switch (key) { + case 'Zenkaku': + case 'Hankaku': + return KeyTable.XK_Zenkaku_Hankaku; + case 'Romaji': + case 'KanaMode': + return KeyTable.XK_Romaji; + } + } + + return DOMKeyTable[key][location]; + } + + // Now we need to look at the Unicode symbol instead + + // Special key? (FIXME: Should have been caught earlier) + if (key.length !== 1) { + return null; + } + + const codepoint = key.charCodeAt(); + if (codepoint) { + return keysyms.lookup(codepoint); + } + + return null; +} diff --git a/web/public/cloud/vendor/novnc/core/input/vkeys.js b/web/public/cloud/vendor/novnc/core/input/vkeys.js new file mode 100644 index 00000000..d848337a --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/vkeys.js @@ -0,0 +1,116 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +/* + * Mapping between Microsoft® Windows® Virtual-Key codes and + * HTML key codes. + */ + +export default { + 0x08: 'Backspace', + 0x09: 'Tab', + 0x0a: 'NumpadClear', + 0x0d: 'Enter', + 0x10: 'ShiftLeft', + 0x11: 'ControlLeft', + 0x12: 'AltLeft', + 0x13: 'Pause', + 0x14: 'CapsLock', + 0x15: 'Lang1', + 0x19: 'Lang2', + 0x1b: 'Escape', + 0x1c: 'Convert', + 0x1d: 'NonConvert', + 0x20: 'Space', + 0x21: 'PageUp', + 0x22: 'PageDown', + 0x23: 'End', + 0x24: 'Home', + 0x25: 'ArrowLeft', + 0x26: 'ArrowUp', + 0x27: 'ArrowRight', + 0x28: 'ArrowDown', + 0x29: 'Select', + 0x2c: 'PrintScreen', + 0x2d: 'Insert', + 0x2e: 'Delete', + 0x2f: 'Help', + 0x30: 'Digit0', + 0x31: 'Digit1', + 0x32: 'Digit2', + 0x33: 'Digit3', + 0x34: 'Digit4', + 0x35: 'Digit5', + 0x36: 'Digit6', + 0x37: 'Digit7', + 0x38: 'Digit8', + 0x39: 'Digit9', + 0x5b: 'MetaLeft', + 0x5c: 'MetaRight', + 0x5d: 'ContextMenu', + 0x5f: 'Sleep', + 0x60: 'Numpad0', + 0x61: 'Numpad1', + 0x62: 'Numpad2', + 0x63: 'Numpad3', + 0x64: 'Numpad4', + 0x65: 'Numpad5', + 0x66: 'Numpad6', + 0x67: 'Numpad7', + 0x68: 'Numpad8', + 0x69: 'Numpad9', + 0x6a: 'NumpadMultiply', + 0x6b: 'NumpadAdd', + 0x6c: 'NumpadDecimal', + 0x6d: 'NumpadSubtract', + 0x6e: 'NumpadDecimal', // Duplicate, because buggy on Windows + 0x6f: 'NumpadDivide', + 0x70: 'F1', + 0x71: 'F2', + 0x72: 'F3', + 0x73: 'F4', + 0x74: 'F5', + 0x75: 'F6', + 0x76: 'F7', + 0x77: 'F8', + 0x78: 'F9', + 0x79: 'F10', + 0x7a: 'F11', + 0x7b: 'F12', + 0x7c: 'F13', + 0x7d: 'F14', + 0x7e: 'F15', + 0x7f: 'F16', + 0x80: 'F17', + 0x81: 'F18', + 0x82: 'F19', + 0x83: 'F20', + 0x84: 'F21', + 0x85: 'F22', + 0x86: 'F23', + 0x87: 'F24', + 0x90: 'NumLock', + 0x91: 'ScrollLock', + 0xa6: 'BrowserBack', + 0xa7: 'BrowserForward', + 0xa8: 'BrowserRefresh', + 0xa9: 'BrowserStop', + 0xaa: 'BrowserSearch', + 0xab: 'BrowserFavorites', + 0xac: 'BrowserHome', + 0xad: 'AudioVolumeMute', + 0xae: 'AudioVolumeDown', + 0xaf: 'AudioVolumeUp', + 0xb0: 'MediaTrackNext', + 0xb1: 'MediaTrackPrevious', + 0xb2: 'MediaStop', + 0xb3: 'MediaPlayPause', + 0xb4: 'LaunchMail', + 0xb5: 'MediaSelect', + 0xb6: 'LaunchApp1', + 0xb7: 'LaunchApp2', + 0xe1: 'AltRight', // Only when it is AltGraph +}; diff --git a/web/public/cloud/vendor/novnc/core/input/xtscancodes.js b/web/public/cloud/vendor/novnc/core/input/xtscancodes.js new file mode 100644 index 00000000..8ab9c17f --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/input/xtscancodes.js @@ -0,0 +1,173 @@ +/* + * This file is auto-generated from keymaps.csv + * Database checksum sha256(76d68c10e97d37fe2ea459e210125ae41796253fb217e900bf2983ade13a7920) + * To re-generate, run: + * keymap-gen code-map --lang=js keymaps.csv html atset1 +*/ +export default { + "Again": 0xe005, /* html:Again (Again) -> linux:129 (KEY_AGAIN) -> atset1:57349 */ + "AltLeft": 0x38, /* html:AltLeft (AltLeft) -> linux:56 (KEY_LEFTALT) -> atset1:56 */ + "AltRight": 0xe038, /* html:AltRight (AltRight) -> linux:100 (KEY_RIGHTALT) -> atset1:57400 */ + "ArrowDown": 0xe050, /* html:ArrowDown (ArrowDown) -> linux:108 (KEY_DOWN) -> atset1:57424 */ + "ArrowLeft": 0xe04b, /* html:ArrowLeft (ArrowLeft) -> linux:105 (KEY_LEFT) -> atset1:57419 */ + "ArrowRight": 0xe04d, /* html:ArrowRight (ArrowRight) -> linux:106 (KEY_RIGHT) -> atset1:57421 */ + "ArrowUp": 0xe048, /* html:ArrowUp (ArrowUp) -> linux:103 (KEY_UP) -> atset1:57416 */ + "AudioVolumeDown": 0xe02e, /* html:AudioVolumeDown (AudioVolumeDown) -> linux:114 (KEY_VOLUMEDOWN) -> atset1:57390 */ + "AudioVolumeMute": 0xe020, /* html:AudioVolumeMute (AudioVolumeMute) -> linux:113 (KEY_MUTE) -> atset1:57376 */ + "AudioVolumeUp": 0xe030, /* html:AudioVolumeUp (AudioVolumeUp) -> linux:115 (KEY_VOLUMEUP) -> atset1:57392 */ + "Backquote": 0x29, /* html:Backquote (Backquote) -> linux:41 (KEY_GRAVE) -> atset1:41 */ + "Backslash": 0x2b, /* html:Backslash (Backslash) -> linux:43 (KEY_BACKSLASH) -> atset1:43 */ + "Backspace": 0xe, /* html:Backspace (Backspace) -> linux:14 (KEY_BACKSPACE) -> atset1:14 */ + "BracketLeft": 0x1a, /* html:BracketLeft (BracketLeft) -> linux:26 (KEY_LEFTBRACE) -> atset1:26 */ + "BracketRight": 0x1b, /* html:BracketRight (BracketRight) -> linux:27 (KEY_RIGHTBRACE) -> atset1:27 */ + "BrowserBack": 0xe06a, /* html:BrowserBack (BrowserBack) -> linux:158 (KEY_BACK) -> atset1:57450 */ + "BrowserFavorites": 0xe066, /* html:BrowserFavorites (BrowserFavorites) -> linux:156 (KEY_BOOKMARKS) -> atset1:57446 */ + "BrowserForward": 0xe069, /* html:BrowserForward (BrowserForward) -> linux:159 (KEY_FORWARD) -> atset1:57449 */ + "BrowserHome": 0xe032, /* html:BrowserHome (BrowserHome) -> linux:172 (KEY_HOMEPAGE) -> atset1:57394 */ + "BrowserRefresh": 0xe067, /* html:BrowserRefresh (BrowserRefresh) -> linux:173 (KEY_REFRESH) -> atset1:57447 */ + "BrowserSearch": 0xe065, /* html:BrowserSearch (BrowserSearch) -> linux:217 (KEY_SEARCH) -> atset1:57445 */ + "BrowserStop": 0xe068, /* html:BrowserStop (BrowserStop) -> linux:128 (KEY_STOP) -> atset1:57448 */ + "CapsLock": 0x3a, /* html:CapsLock (CapsLock) -> linux:58 (KEY_CAPSLOCK) -> atset1:58 */ + "Comma": 0x33, /* html:Comma (Comma) -> linux:51 (KEY_COMMA) -> atset1:51 */ + "ContextMenu": 0xe05d, /* html:ContextMenu (ContextMenu) -> linux:127 (KEY_COMPOSE) -> atset1:57437 */ + "ControlLeft": 0x1d, /* html:ControlLeft (ControlLeft) -> linux:29 (KEY_LEFTCTRL) -> atset1:29 */ + "ControlRight": 0xe01d, /* html:ControlRight (ControlRight) -> linux:97 (KEY_RIGHTCTRL) -> atset1:57373 */ + "Convert": 0x79, /* html:Convert (Convert) -> linux:92 (KEY_HENKAN) -> atset1:121 */ + "Copy": 0xe078, /* html:Copy (Copy) -> linux:133 (KEY_COPY) -> atset1:57464 */ + "Cut": 0xe03c, /* html:Cut (Cut) -> linux:137 (KEY_CUT) -> atset1:57404 */ + "Delete": 0xe053, /* html:Delete (Delete) -> linux:111 (KEY_DELETE) -> atset1:57427 */ + "Digit0": 0xb, /* html:Digit0 (Digit0) -> linux:11 (KEY_0) -> atset1:11 */ + "Digit1": 0x2, /* html:Digit1 (Digit1) -> linux:2 (KEY_1) -> atset1:2 */ + "Digit2": 0x3, /* html:Digit2 (Digit2) -> linux:3 (KEY_2) -> atset1:3 */ + "Digit3": 0x4, /* html:Digit3 (Digit3) -> linux:4 (KEY_3) -> atset1:4 */ + "Digit4": 0x5, /* html:Digit4 (Digit4) -> linux:5 (KEY_4) -> atset1:5 */ + "Digit5": 0x6, /* html:Digit5 (Digit5) -> linux:6 (KEY_5) -> atset1:6 */ + "Digit6": 0x7, /* html:Digit6 (Digit6) -> linux:7 (KEY_6) -> atset1:7 */ + "Digit7": 0x8, /* html:Digit7 (Digit7) -> linux:8 (KEY_7) -> atset1:8 */ + "Digit8": 0x9, /* html:Digit8 (Digit8) -> linux:9 (KEY_8) -> atset1:9 */ + "Digit9": 0xa, /* html:Digit9 (Digit9) -> linux:10 (KEY_9) -> atset1:10 */ + "Eject": 0xe07d, /* html:Eject (Eject) -> linux:162 (KEY_EJECTCLOSECD) -> atset1:57469 */ + "End": 0xe04f, /* html:End (End) -> linux:107 (KEY_END) -> atset1:57423 */ + "Enter": 0x1c, /* html:Enter (Enter) -> linux:28 (KEY_ENTER) -> atset1:28 */ + "Equal": 0xd, /* html:Equal (Equal) -> linux:13 (KEY_EQUAL) -> atset1:13 */ + "Escape": 0x1, /* html:Escape (Escape) -> linux:1 (KEY_ESC) -> atset1:1 */ + "F1": 0x3b, /* html:F1 (F1) -> linux:59 (KEY_F1) -> atset1:59 */ + "F10": 0x44, /* html:F10 (F10) -> linux:68 (KEY_F10) -> atset1:68 */ + "F11": 0x57, /* html:F11 (F11) -> linux:87 (KEY_F11) -> atset1:87 */ + "F12": 0x58, /* html:F12 (F12) -> linux:88 (KEY_F12) -> atset1:88 */ + "F13": 0x5d, /* html:F13 (F13) -> linux:183 (KEY_F13) -> atset1:93 */ + "F14": 0x5e, /* html:F14 (F14) -> linux:184 (KEY_F14) -> atset1:94 */ + "F15": 0x5f, /* html:F15 (F15) -> linux:185 (KEY_F15) -> atset1:95 */ + "F16": 0x55, /* html:F16 (F16) -> linux:186 (KEY_F16) -> atset1:85 */ + "F17": 0xe003, /* html:F17 (F17) -> linux:187 (KEY_F17) -> atset1:57347 */ + "F18": 0xe077, /* html:F18 (F18) -> linux:188 (KEY_F18) -> atset1:57463 */ + "F19": 0xe004, /* html:F19 (F19) -> linux:189 (KEY_F19) -> atset1:57348 */ + "F2": 0x3c, /* html:F2 (F2) -> linux:60 (KEY_F2) -> atset1:60 */ + "F20": 0x5a, /* html:F20 (F20) -> linux:190 (KEY_F20) -> atset1:90 */ + "F21": 0x74, /* html:F21 (F21) -> linux:191 (KEY_F21) -> atset1:116 */ + "F22": 0xe079, /* html:F22 (F22) -> linux:192 (KEY_F22) -> atset1:57465 */ + "F23": 0x6d, /* html:F23 (F23) -> linux:193 (KEY_F23) -> atset1:109 */ + "F24": 0x6f, /* html:F24 (F24) -> linux:194 (KEY_F24) -> atset1:111 */ + "F3": 0x3d, /* html:F3 (F3) -> linux:61 (KEY_F3) -> atset1:61 */ + "F4": 0x3e, /* html:F4 (F4) -> linux:62 (KEY_F4) -> atset1:62 */ + "F5": 0x3f, /* html:F5 (F5) -> linux:63 (KEY_F5) -> atset1:63 */ + "F6": 0x40, /* html:F6 (F6) -> linux:64 (KEY_F6) -> atset1:64 */ + "F7": 0x41, /* html:F7 (F7) -> linux:65 (KEY_F7) -> atset1:65 */ + "F8": 0x42, /* html:F8 (F8) -> linux:66 (KEY_F8) -> atset1:66 */ + "F9": 0x43, /* html:F9 (F9) -> linux:67 (KEY_F9) -> atset1:67 */ + "Find": 0xe041, /* html:Find (Find) -> linux:136 (KEY_FIND) -> atset1:57409 */ + "Help": 0xe075, /* html:Help (Help) -> linux:138 (KEY_HELP) -> atset1:57461 */ + "Hiragana": 0x77, /* html:Hiragana (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */ + "Home": 0xe047, /* html:Home (Home) -> linux:102 (KEY_HOME) -> atset1:57415 */ + "Insert": 0xe052, /* html:Insert (Insert) -> linux:110 (KEY_INSERT) -> atset1:57426 */ + "IntlBackslash": 0x56, /* html:IntlBackslash (IntlBackslash) -> linux:86 (KEY_102ND) -> atset1:86 */ + "IntlRo": 0x73, /* html:IntlRo (IntlRo) -> linux:89 (KEY_RO) -> atset1:115 */ + "IntlYen": 0x7d, /* html:IntlYen (IntlYen) -> linux:124 (KEY_YEN) -> atset1:125 */ + "KanaMode": 0x70, /* html:KanaMode (KanaMode) -> linux:93 (KEY_KATAKANAHIRAGANA) -> atset1:112 */ + "Katakana": 0x78, /* html:Katakana (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */ + "KeyA": 0x1e, /* html:KeyA (KeyA) -> linux:30 (KEY_A) -> atset1:30 */ + "KeyB": 0x30, /* html:KeyB (KeyB) -> linux:48 (KEY_B) -> atset1:48 */ + "KeyC": 0x2e, /* html:KeyC (KeyC) -> linux:46 (KEY_C) -> atset1:46 */ + "KeyD": 0x20, /* html:KeyD (KeyD) -> linux:32 (KEY_D) -> atset1:32 */ + "KeyE": 0x12, /* html:KeyE (KeyE) -> linux:18 (KEY_E) -> atset1:18 */ + "KeyF": 0x21, /* html:KeyF (KeyF) -> linux:33 (KEY_F) -> atset1:33 */ + "KeyG": 0x22, /* html:KeyG (KeyG) -> linux:34 (KEY_G) -> atset1:34 */ + "KeyH": 0x23, /* html:KeyH (KeyH) -> linux:35 (KEY_H) -> atset1:35 */ + "KeyI": 0x17, /* html:KeyI (KeyI) -> linux:23 (KEY_I) -> atset1:23 */ + "KeyJ": 0x24, /* html:KeyJ (KeyJ) -> linux:36 (KEY_J) -> atset1:36 */ + "KeyK": 0x25, /* html:KeyK (KeyK) -> linux:37 (KEY_K) -> atset1:37 */ + "KeyL": 0x26, /* html:KeyL (KeyL) -> linux:38 (KEY_L) -> atset1:38 */ + "KeyM": 0x32, /* html:KeyM (KeyM) -> linux:50 (KEY_M) -> atset1:50 */ + "KeyN": 0x31, /* html:KeyN (KeyN) -> linux:49 (KEY_N) -> atset1:49 */ + "KeyO": 0x18, /* html:KeyO (KeyO) -> linux:24 (KEY_O) -> atset1:24 */ + "KeyP": 0x19, /* html:KeyP (KeyP) -> linux:25 (KEY_P) -> atset1:25 */ + "KeyQ": 0x10, /* html:KeyQ (KeyQ) -> linux:16 (KEY_Q) -> atset1:16 */ + "KeyR": 0x13, /* html:KeyR (KeyR) -> linux:19 (KEY_R) -> atset1:19 */ + "KeyS": 0x1f, /* html:KeyS (KeyS) -> linux:31 (KEY_S) -> atset1:31 */ + "KeyT": 0x14, /* html:KeyT (KeyT) -> linux:20 (KEY_T) -> atset1:20 */ + "KeyU": 0x16, /* html:KeyU (KeyU) -> linux:22 (KEY_U) -> atset1:22 */ + "KeyV": 0x2f, /* html:KeyV (KeyV) -> linux:47 (KEY_V) -> atset1:47 */ + "KeyW": 0x11, /* html:KeyW (KeyW) -> linux:17 (KEY_W) -> atset1:17 */ + "KeyX": 0x2d, /* html:KeyX (KeyX) -> linux:45 (KEY_X) -> atset1:45 */ + "KeyY": 0x15, /* html:KeyY (KeyY) -> linux:21 (KEY_Y) -> atset1:21 */ + "KeyZ": 0x2c, /* html:KeyZ (KeyZ) -> linux:44 (KEY_Z) -> atset1:44 */ + "Lang1": 0x72, /* html:Lang1 (Lang1) -> linux:122 (KEY_HANGEUL) -> atset1:114 */ + "Lang2": 0x71, /* html:Lang2 (Lang2) -> linux:123 (KEY_HANJA) -> atset1:113 */ + "Lang3": 0x78, /* html:Lang3 (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */ + "Lang4": 0x77, /* html:Lang4 (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */ + "Lang5": 0x76, /* html:Lang5 (Lang5) -> linux:85 (KEY_ZENKAKUHANKAKU) -> atset1:118 */ + "LaunchApp1": 0xe06b, /* html:LaunchApp1 (LaunchApp1) -> linux:157 (KEY_COMPUTER) -> atset1:57451 */ + "LaunchApp2": 0xe021, /* html:LaunchApp2 (LaunchApp2) -> linux:140 (KEY_CALC) -> atset1:57377 */ + "LaunchMail": 0xe06c, /* html:LaunchMail (LaunchMail) -> linux:155 (KEY_MAIL) -> atset1:57452 */ + "MediaPlayPause": 0xe022, /* html:MediaPlayPause (MediaPlayPause) -> linux:164 (KEY_PLAYPAUSE) -> atset1:57378 */ + "MediaSelect": 0xe06d, /* html:MediaSelect (MediaSelect) -> linux:226 (KEY_MEDIA) -> atset1:57453 */ + "MediaStop": 0xe024, /* html:MediaStop (MediaStop) -> linux:166 (KEY_STOPCD) -> atset1:57380 */ + "MediaTrackNext": 0xe019, /* html:MediaTrackNext (MediaTrackNext) -> linux:163 (KEY_NEXTSONG) -> atset1:57369 */ + "MediaTrackPrevious": 0xe010, /* html:MediaTrackPrevious (MediaTrackPrevious) -> linux:165 (KEY_PREVIOUSSONG) -> atset1:57360 */ + "MetaLeft": 0xe05b, /* html:MetaLeft (MetaLeft) -> linux:125 (KEY_LEFTMETA) -> atset1:57435 */ + "MetaRight": 0xe05c, /* html:MetaRight (MetaRight) -> linux:126 (KEY_RIGHTMETA) -> atset1:57436 */ + "Minus": 0xc, /* html:Minus (Minus) -> linux:12 (KEY_MINUS) -> atset1:12 */ + "NonConvert": 0x7b, /* html:NonConvert (NonConvert) -> linux:94 (KEY_MUHENKAN) -> atset1:123 */ + "NumLock": 0x45, /* html:NumLock (NumLock) -> linux:69 (KEY_NUMLOCK) -> atset1:69 */ + "Numpad0": 0x52, /* html:Numpad0 (Numpad0) -> linux:82 (KEY_KP0) -> atset1:82 */ + "Numpad1": 0x4f, /* html:Numpad1 (Numpad1) -> linux:79 (KEY_KP1) -> atset1:79 */ + "Numpad2": 0x50, /* html:Numpad2 (Numpad2) -> linux:80 (KEY_KP2) -> atset1:80 */ + "Numpad3": 0x51, /* html:Numpad3 (Numpad3) -> linux:81 (KEY_KP3) -> atset1:81 */ + "Numpad4": 0x4b, /* html:Numpad4 (Numpad4) -> linux:75 (KEY_KP4) -> atset1:75 */ + "Numpad5": 0x4c, /* html:Numpad5 (Numpad5) -> linux:76 (KEY_KP5) -> atset1:76 */ + "Numpad6": 0x4d, /* html:Numpad6 (Numpad6) -> linux:77 (KEY_KP6) -> atset1:77 */ + "Numpad7": 0x47, /* html:Numpad7 (Numpad7) -> linux:71 (KEY_KP7) -> atset1:71 */ + "Numpad8": 0x48, /* html:Numpad8 (Numpad8) -> linux:72 (KEY_KP8) -> atset1:72 */ + "Numpad9": 0x49, /* html:Numpad9 (Numpad9) -> linux:73 (KEY_KP9) -> atset1:73 */ + "NumpadAdd": 0x4e, /* html:NumpadAdd (NumpadAdd) -> linux:78 (KEY_KPPLUS) -> atset1:78 */ + "NumpadComma": 0x7e, /* html:NumpadComma (NumpadComma) -> linux:121 (KEY_KPCOMMA) -> atset1:126 */ + "NumpadDecimal": 0x53, /* html:NumpadDecimal (NumpadDecimal) -> linux:83 (KEY_KPDOT) -> atset1:83 */ + "NumpadDivide": 0xe035, /* html:NumpadDivide (NumpadDivide) -> linux:98 (KEY_KPSLASH) -> atset1:57397 */ + "NumpadEnter": 0xe01c, /* html:NumpadEnter (NumpadEnter) -> linux:96 (KEY_KPENTER) -> atset1:57372 */ + "NumpadEqual": 0x59, /* html:NumpadEqual (NumpadEqual) -> linux:117 (KEY_KPEQUAL) -> atset1:89 */ + "NumpadMultiply": 0x37, /* html:NumpadMultiply (NumpadMultiply) -> linux:55 (KEY_KPASTERISK) -> atset1:55 */ + "NumpadParenLeft": 0xe076, /* html:NumpadParenLeft (NumpadParenLeft) -> linux:179 (KEY_KPLEFTPAREN) -> atset1:57462 */ + "NumpadParenRight": 0xe07b, /* html:NumpadParenRight (NumpadParenRight) -> linux:180 (KEY_KPRIGHTPAREN) -> atset1:57467 */ + "NumpadSubtract": 0x4a, /* html:NumpadSubtract (NumpadSubtract) -> linux:74 (KEY_KPMINUS) -> atset1:74 */ + "Open": 0x64, /* html:Open (Open) -> linux:134 (KEY_OPEN) -> atset1:100 */ + "PageDown": 0xe051, /* html:PageDown (PageDown) -> linux:109 (KEY_PAGEDOWN) -> atset1:57425 */ + "PageUp": 0xe049, /* html:PageUp (PageUp) -> linux:104 (KEY_PAGEUP) -> atset1:57417 */ + "Paste": 0x65, /* html:Paste (Paste) -> linux:135 (KEY_PASTE) -> atset1:101 */ + "Pause": 0xe046, /* html:Pause (Pause) -> linux:119 (KEY_PAUSE) -> atset1:57414 */ + "Period": 0x34, /* html:Period (Period) -> linux:52 (KEY_DOT) -> atset1:52 */ + "Power": 0xe05e, /* html:Power (Power) -> linux:116 (KEY_POWER) -> atset1:57438 */ + "PrintScreen": 0x54, /* html:PrintScreen (PrintScreen) -> linux:99 (KEY_SYSRQ) -> atset1:84 */ + "Props": 0xe006, /* html:Props (Props) -> linux:130 (KEY_PROPS) -> atset1:57350 */ + "Quote": 0x28, /* html:Quote (Quote) -> linux:40 (KEY_APOSTROPHE) -> atset1:40 */ + "ScrollLock": 0x46, /* html:ScrollLock (ScrollLock) -> linux:70 (KEY_SCROLLLOCK) -> atset1:70 */ + "Semicolon": 0x27, /* html:Semicolon (Semicolon) -> linux:39 (KEY_SEMICOLON) -> atset1:39 */ + "ShiftLeft": 0x2a, /* html:ShiftLeft (ShiftLeft) -> linux:42 (KEY_LEFTSHIFT) -> atset1:42 */ + "ShiftRight": 0x36, /* html:ShiftRight (ShiftRight) -> linux:54 (KEY_RIGHTSHIFT) -> atset1:54 */ + "Slash": 0x35, /* html:Slash (Slash) -> linux:53 (KEY_SLASH) -> atset1:53 */ + "Sleep": 0xe05f, /* html:Sleep (Sleep) -> linux:142 (KEY_SLEEP) -> atset1:57439 */ + "Space": 0x39, /* html:Space (Space) -> linux:57 (KEY_SPACE) -> atset1:57 */ + "Suspend": 0xe025, /* html:Suspend (Suspend) -> linux:205 (KEY_SUSPEND) -> atset1:57381 */ + "Tab": 0xf, /* html:Tab (Tab) -> linux:15 (KEY_TAB) -> atset1:15 */ + "Undo": 0xe007, /* html:Undo (Undo) -> linux:131 (KEY_UNDO) -> atset1:57351 */ + "WakeUp": 0xe063, /* html:WakeUp (WakeUp) -> linux:143 (KEY_WAKEUP) -> atset1:57443 */ +}; diff --git a/web/public/cloud/vendor/novnc/core/ra2.js b/web/public/cloud/vendor/novnc/core/ra2.js new file mode 100644 index 00000000..d330b848 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/ra2.js @@ -0,0 +1,312 @@ +import { encodeUTF8 } from './util/strings.js'; +import EventTargetMixin from './util/eventtarget.js'; +import legacyCrypto from './crypto/crypto.js'; + +class RA2Cipher { + constructor() { + this._cipher = null; + this._counter = new Uint8Array(16); + } + + async setKey(key) { + this._cipher = await legacyCrypto.importKey( + "raw", key, { name: "AES-EAX" }, false, ["encrypt, decrypt"]); + } + + async makeMessage(message) { + const ad = new Uint8Array([(message.length & 0xff00) >>> 8, message.length & 0xff]); + const encrypted = await legacyCrypto.encrypt({ + name: "AES-EAX", + iv: this._counter, + additionalData: ad, + }, this._cipher, message); + for (let i = 0; i < 16 && this._counter[i]++ === 255; i++); + const res = new Uint8Array(message.length + 2 + 16); + res.set(ad); + res.set(encrypted, 2); + return res; + } + + async receiveMessage(length, encrypted) { + const ad = new Uint8Array([(length & 0xff00) >>> 8, length & 0xff]); + const res = await legacyCrypto.decrypt({ + name: "AES-EAX", + iv: this._counter, + additionalData: ad, + }, this._cipher, encrypted); + for (let i = 0; i < 16 && this._counter[i]++ === 255; i++); + return res; + } +} + +export default class RSAAESAuthenticationState extends EventTargetMixin { + constructor(sock, getCredentials) { + super(); + this._hasStarted = false; + this._checkSock = null; + this._checkCredentials = null; + this._approveServerResolve = null; + this._sockReject = null; + this._credentialsReject = null; + this._approveServerReject = null; + this._sock = sock; + this._getCredentials = getCredentials; + } + + _waitSockAsync(len) { + return new Promise((resolve, reject) => { + const hasData = () => !this._sock.rQwait('RA2', len); + if (hasData()) { + resolve(); + } else { + this._checkSock = () => { + if (hasData()) { + resolve(); + this._checkSock = null; + this._sockReject = null; + } + }; + this._sockReject = reject; + } + }); + } + + _waitApproveKeyAsync() { + return new Promise((resolve, reject) => { + this._approveServerResolve = resolve; + this._approveServerReject = reject; + }); + } + + _waitCredentialsAsync(subtype) { + const hasCredentials = () => { + if (subtype === 1 && this._getCredentials().username !== undefined && + this._getCredentials().password !== undefined) { + return true; + } else if (subtype === 2 && this._getCredentials().password !== undefined) { + return true; + } + return false; + }; + return new Promise((resolve, reject) => { + if (hasCredentials()) { + resolve(); + } else { + this._checkCredentials = () => { + if (hasCredentials()) { + resolve(); + this._checkCredentials = null; + this._credentialsReject = null; + } + }; + this._credentialsReject = reject; + } + }); + } + + checkInternalEvents() { + if (this._checkSock !== null) { + this._checkSock(); + } + if (this._checkCredentials !== null) { + this._checkCredentials(); + } + } + + approveServer() { + if (this._approveServerResolve !== null) { + this._approveServerResolve(); + this._approveServerResolve = null; + } + } + + disconnect() { + if (this._sockReject !== null) { + this._sockReject(new Error("disconnect normally")); + this._sockReject = null; + } + if (this._credentialsReject !== null) { + this._credentialsReject(new Error("disconnect normally")); + this._credentialsReject = null; + } + if (this._approveServerReject !== null) { + this._approveServerReject(new Error("disconnect normally")); + this._approveServerReject = null; + } + } + + async negotiateRA2neAuthAsync() { + this._hasStarted = true; + // 1: Receive server public key + await this._waitSockAsync(4); + const serverKeyLengthBuffer = this._sock.rQpeekBytes(4); + const serverKeyLength = this._sock.rQshift32(); + if (serverKeyLength < 1024) { + throw new Error("RA2: server public key is too short: " + serverKeyLength); + } else if (serverKeyLength > 8192) { + throw new Error("RA2: server public key is too long: " + serverKeyLength); + } + const serverKeyBytes = Math.ceil(serverKeyLength / 8); + await this._waitSockAsync(serverKeyBytes * 2); + const serverN = this._sock.rQshiftBytes(serverKeyBytes); + const serverE = this._sock.rQshiftBytes(serverKeyBytes); + const serverRSACipher = await legacyCrypto.importKey( + "raw", { n: serverN, e: serverE }, { name: "RSA-PKCS1-v1_5" }, false, ["encrypt"]); + const serverPublickey = new Uint8Array(4 + serverKeyBytes * 2); + serverPublickey.set(serverKeyLengthBuffer); + serverPublickey.set(serverN, 4); + serverPublickey.set(serverE, 4 + serverKeyBytes); + + // verify server public key + let approveKey = this._waitApproveKeyAsync(); + this.dispatchEvent(new CustomEvent("serververification", { + detail: { type: "RSA", publickey: serverPublickey } + })); + await approveKey; + + // 2: Send client public key + const clientKeyLength = 2048; + const clientKeyBytes = Math.ceil(clientKeyLength / 8); + const clientRSACipher = (await legacyCrypto.generateKey({ + name: "RSA-PKCS1-v1_5", + modulusLength: clientKeyLength, + publicExponent: new Uint8Array([1, 0, 1]), + }, true, ["encrypt"])).privateKey; + const clientExportedRSAKey = await legacyCrypto.exportKey("raw", clientRSACipher); + const clientN = clientExportedRSAKey.n; + const clientE = clientExportedRSAKey.e; + const clientPublicKey = new Uint8Array(4 + clientKeyBytes * 2); + clientPublicKey[0] = (clientKeyLength & 0xff000000) >>> 24; + clientPublicKey[1] = (clientKeyLength & 0xff0000) >>> 16; + clientPublicKey[2] = (clientKeyLength & 0xff00) >>> 8; + clientPublicKey[3] = clientKeyLength & 0xff; + clientPublicKey.set(clientN, 4); + clientPublicKey.set(clientE, 4 + clientKeyBytes); + this._sock.sQpushBytes(clientPublicKey); + this._sock.flush(); + + // 3: Send client random + const clientRandom = new Uint8Array(16); + window.crypto.getRandomValues(clientRandom); + const clientEncryptedRandom = await legacyCrypto.encrypt( + { name: "RSA-PKCS1-v1_5" }, serverRSACipher, clientRandom); + const clientRandomMessage = new Uint8Array(2 + serverKeyBytes); + clientRandomMessage[0] = (serverKeyBytes & 0xff00) >>> 8; + clientRandomMessage[1] = serverKeyBytes & 0xff; + clientRandomMessage.set(clientEncryptedRandom, 2); + this._sock.sQpushBytes(clientRandomMessage); + this._sock.flush(); + + // 4: Receive server random + await this._waitSockAsync(2); + if (this._sock.rQshift16() !== clientKeyBytes) { + throw new Error("RA2: wrong encrypted message length"); + } + const serverEncryptedRandom = this._sock.rQshiftBytes(clientKeyBytes); + const serverRandom = await legacyCrypto.decrypt( + { name: "RSA-PKCS1-v1_5" }, clientRSACipher, serverEncryptedRandom); + if (serverRandom === null || serverRandom.length !== 16) { + throw new Error("RA2: corrupted server encrypted random"); + } + + // 5: Compute session keys and set ciphers + let clientSessionKey = new Uint8Array(32); + let serverSessionKey = new Uint8Array(32); + clientSessionKey.set(serverRandom); + clientSessionKey.set(clientRandom, 16); + serverSessionKey.set(clientRandom); + serverSessionKey.set(serverRandom, 16); + clientSessionKey = await window.crypto.subtle.digest("SHA-1", clientSessionKey); + clientSessionKey = new Uint8Array(clientSessionKey).slice(0, 16); + serverSessionKey = await window.crypto.subtle.digest("SHA-1", serverSessionKey); + serverSessionKey = new Uint8Array(serverSessionKey).slice(0, 16); + const clientCipher = new RA2Cipher(); + await clientCipher.setKey(clientSessionKey); + const serverCipher = new RA2Cipher(); + await serverCipher.setKey(serverSessionKey); + + // 6: Compute and exchange hashes + let serverHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2); + let clientHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2); + serverHash.set(serverPublickey); + serverHash.set(clientPublicKey, 4 + serverKeyBytes * 2); + clientHash.set(clientPublicKey); + clientHash.set(serverPublickey, 4 + clientKeyBytes * 2); + serverHash = await window.crypto.subtle.digest("SHA-1", serverHash); + clientHash = await window.crypto.subtle.digest("SHA-1", clientHash); + serverHash = new Uint8Array(serverHash); + clientHash = new Uint8Array(clientHash); + this._sock.sQpushBytes(await clientCipher.makeMessage(clientHash)); + this._sock.flush(); + await this._waitSockAsync(2 + 20 + 16); + if (this._sock.rQshift16() !== 20) { + throw new Error("RA2: wrong server hash"); + } + const serverHashReceived = await serverCipher.receiveMessage( + 20, this._sock.rQshiftBytes(20 + 16)); + if (serverHashReceived === null) { + throw new Error("RA2: failed to authenticate the message"); + } + for (let i = 0; i < 20; i++) { + if (serverHashReceived[i] !== serverHash[i]) { + throw new Error("RA2: wrong server hash"); + } + } + + // 7: Receive subtype + await this._waitSockAsync(2 + 1 + 16); + if (this._sock.rQshift16() !== 1) { + throw new Error("RA2: wrong subtype"); + } + let subtype = (await serverCipher.receiveMessage( + 1, this._sock.rQshiftBytes(1 + 16))); + if (subtype === null) { + throw new Error("RA2: failed to authenticate the message"); + } + subtype = subtype[0]; + let waitCredentials = this._waitCredentialsAsync(subtype); + if (subtype === 1) { + if (this._getCredentials().username === undefined || + this._getCredentials().password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + } + } else if (subtype === 2) { + if (this._getCredentials().password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["password"] } })); + } + } else { + throw new Error("RA2: wrong subtype"); + } + await waitCredentials; + let username; + if (subtype === 1) { + username = encodeUTF8(this._getCredentials().username).slice(0, 255); + } else { + username = ""; + } + const password = encodeUTF8(this._getCredentials().password).slice(0, 255); + const credentials = new Uint8Array(username.length + password.length + 2); + credentials[0] = username.length; + credentials[username.length + 1] = password.length; + for (let i = 0; i < username.length; i++) { + credentials[i + 1] = username.charCodeAt(i); + } + for (let i = 0; i < password.length; i++) { + credentials[username.length + 2 + i] = password.charCodeAt(i); + } + this._sock.sQpushBytes(await clientCipher.makeMessage(credentials)); + this._sock.flush(); + } + + get hasStarted() { + return this._hasStarted; + } + + set hasStarted(s) { + this._hasStarted = s; + } +} diff --git a/web/public/cloud/vendor/novnc/core/rfb.js b/web/public/cloud/vendor/novnc/core/rfb.js new file mode 100644 index 00000000..80011e4a --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/rfb.js @@ -0,0 +1,3411 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +import { toUnsigned32bit, toSigned32bit } from './util/int.js'; +import * as Log from './util/logging.js'; +import { encodeUTF8, decodeUTF8 } from './util/strings.js'; +import { dragThreshold, supportsWebCodecsH264Decode } from './util/browser.js'; +import { clientToElement } from './util/element.js'; +import { setCapture } from './util/events.js'; +import EventTargetMixin from './util/eventtarget.js'; +import Display from "./display.js"; +import Inflator from "./inflator.js"; +import Deflator from "./deflator.js"; +import Keyboard from "./input/keyboard.js"; +import GestureHandler from "./input/gesturehandler.js"; +import Cursor from "./util/cursor.js"; +import Websock from "./websock.js"; +import KeyTable from "./input/keysym.js"; +import XtScancode from "./input/xtscancodes.js"; +import { encodings } from "./encodings.js"; +import RSAAESAuthenticationState from "./ra2.js"; +import legacyCrypto from "./crypto/crypto.js"; + +import RawDecoder from "./decoders/raw.js"; +import CopyRectDecoder from "./decoders/copyrect.js"; +import RREDecoder from "./decoders/rre.js"; +import HextileDecoder from "./decoders/hextile.js"; +import ZlibDecoder from './decoders/zlib.js'; +import TightDecoder from "./decoders/tight.js"; +import TightPNGDecoder from "./decoders/tightpng.js"; +import ZRLEDecoder from "./decoders/zrle.js"; +import JPEGDecoder from "./decoders/jpeg.js"; +import H264Decoder from "./decoders/h264.js"; + +// How many seconds to wait for a disconnect to finish +const DISCONNECT_TIMEOUT = 3; +const DEFAULT_BACKGROUND = 'rgb(40, 40, 40)'; + +// Minimum wait (ms) between two mouse moves +const MOUSE_MOVE_DELAY = 17; + +// Wheel thresholds +const WHEEL_STEP = 50; // Pixels needed for one step +const WHEEL_LINE_HEIGHT = 19; // Assumed pixels for one line step + +// Gesture thresholds +const GESTURE_ZOOMSENS = 75; +const GESTURE_SCRLSENS = 50; +const DOUBLE_TAP_TIMEOUT = 1000; +const DOUBLE_TAP_THRESHOLD = 50; + +// Security types +const securityTypeNone = 1; +const securityTypeVNCAuth = 2; +const securityTypeRA2ne = 6; +const securityTypeTight = 16; +const securityTypeVeNCrypt = 19; +const securityTypeXVP = 22; +const securityTypeARD = 30; +const securityTypeMSLogonII = 113; + +// Special Tight security types +const securityTypeUnixLogon = 129; + +// VeNCrypt security types +const securityTypePlain = 256; + +// Extended clipboard pseudo-encoding formats +const extendedClipboardFormatText = 1; +/*eslint-disable no-unused-vars */ +const extendedClipboardFormatRtf = 1 << 1; +const extendedClipboardFormatHtml = 1 << 2; +const extendedClipboardFormatDib = 1 << 3; +const extendedClipboardFormatFiles = 1 << 4; +/*eslint-enable */ + +// Extended clipboard pseudo-encoding actions +const extendedClipboardActionCaps = 1 << 24; +const extendedClipboardActionRequest = 1 << 25; +const extendedClipboardActionPeek = 1 << 26; +const extendedClipboardActionNotify = 1 << 27; +const extendedClipboardActionProvide = 1 << 28; + +export default class RFB extends EventTargetMixin { + constructor(target, urlOrChannel, options) { + if (!target) { + throw new Error("Must specify target"); + } + if (!urlOrChannel) { + throw new Error("Must specify URL, WebSocket or RTCDataChannel"); + } + + // We rely on modern APIs which might not be available in an + // insecure context + if (!window.isSecureContext) { + Log.Error("noVNC requires a secure context (TLS). Expect crashes!"); + } + + super(); + + this._target = target; + + if (typeof urlOrChannel === "string") { + this._url = urlOrChannel; + } else { + this._url = null; + this._rawChannel = urlOrChannel; + } + + // Connection details + options = options || {}; + this._rfbCredentials = options.credentials || {}; + this._shared = 'shared' in options ? !!options.shared : true; + this._repeaterID = options.repeaterID || ''; + this._wsProtocols = options.wsProtocols || []; + + // Internal state + this._rfbConnectionState = ''; + this._rfbInitState = ''; + this._rfbAuthScheme = -1; + this._rfbCleanDisconnect = true; + this._rfbRSAAESAuthenticationState = null; + + // Server capabilities + this._rfbVersion = 0; + this._rfbMaxVersion = 3.8; + this._rfbTightVNC = false; + this._rfbVeNCryptState = 0; + this._rfbXvpVer = 0; + + this._fbWidth = 0; + this._fbHeight = 0; + + this._fbName = ""; + + this._capabilities = { power: false }; + + this._supportsFence = false; + + this._supportsContinuousUpdates = false; + this._enabledContinuousUpdates = false; + + this._supportsSetDesktopSize = false; + this._screenID = 0; + this._screenFlags = 0; + this._pendingRemoteResize = false; + this._lastResize = 0; + + this._qemuExtKeyEventSupported = false; + + this._extendedPointerEventSupported = false; + + this._clipboardText = null; + this._clipboardServerCapabilitiesActions = {}; + this._clipboardServerCapabilitiesFormats = {}; + + // Internal objects + this._sock = null; // Websock object + this._display = null; // Display object + this._flushing = false; // Display flushing state + this._keyboard = null; // Keyboard input handler object + this._gestures = null; // Gesture input handler object + this._resizeObserver = null; // Resize observer object + + // Timers + this._disconnTimer = null; // disconnection timer + this._resizeTimeout = null; // resize rate limiting + this._mouseMoveTimer = null; + + // Decoder states + this._decoders = {}; + + this._FBU = { + rects: 0, + x: 0, + y: 0, + width: 0, + height: 0, + encoding: null, + }; + + // Mouse state + this._mousePos = {}; + this._mouseButtonMask = 0; + this._mouseLastMoveTime = 0; + this._viewportDragging = false; + this._viewportDragPos = {}; + this._viewportHasMoved = false; + this._accumulatedWheelDeltaX = 0; + this._accumulatedWheelDeltaY = 0; + + // Gesture state + this._gestureLastTapTime = null; + this._gestureFirstDoubleTapEv = null; + this._gestureLastMagnitudeX = 0; + this._gestureLastMagnitudeY = 0; + + // Bound event handlers + this._eventHandlers = { + focusCanvas: this._focusCanvas.bind(this), + handleResize: this._handleResize.bind(this), + handleMouse: this._handleMouse.bind(this), + handleWheel: this._handleWheel.bind(this), + handleGesture: this._handleGesture.bind(this), + handleRSAAESCredentialsRequired: this._handleRSAAESCredentialsRequired.bind(this), + handleRSAAESServerVerification: this._handleRSAAESServerVerification.bind(this), + }; + + // main setup + Log.Debug(">> RFB.constructor"); + + // Create DOM elements + this._screen = document.createElement('div'); + this._screen.style.display = 'flex'; + this._screen.style.width = '100%'; + this._screen.style.height = '100%'; + this._screen.style.overflow = 'auto'; + this._screen.style.background = DEFAULT_BACKGROUND; + this._canvas = document.createElement('canvas'); + this._canvas.style.margin = 'auto'; + // Some browsers add an outline on focus + this._canvas.style.outline = 'none'; + this._canvas.width = 0; + this._canvas.height = 0; + this._canvas.tabIndex = -1; + this._screen.appendChild(this._canvas); + + // Cursor + this._cursor = new Cursor(); + + // XXX: TightVNC 2.8.11 sends no cursor at all until Windows changes + // it. Result: no cursor at all until a window border or an edit field + // is hit blindly. But there are also VNC servers that draw the cursor + // in the framebuffer and don't send the empty local cursor. There is + // no way to satisfy both sides. + // + // The spec is unclear on this "initial cursor" issue. Many other + // viewers (TigerVNC, RealVNC, Remmina) display an arrow as the + // initial cursor instead. + this._cursorImage = RFB.cursors.none; + + // populate decoder array with objects + this._decoders[encodings.encodingRaw] = new RawDecoder(); + this._decoders[encodings.encodingCopyRect] = new CopyRectDecoder(); + this._decoders[encodings.encodingRRE] = new RREDecoder(); + this._decoders[encodings.encodingHextile] = new HextileDecoder(); + this._decoders[encodings.encodingZlib] = new ZlibDecoder(); + this._decoders[encodings.encodingTight] = new TightDecoder(); + this._decoders[encodings.encodingTightPNG] = new TightPNGDecoder(); + this._decoders[encodings.encodingZRLE] = new ZRLEDecoder(); + this._decoders[encodings.encodingJPEG] = new JPEGDecoder(); + this._decoders[encodings.encodingH264] = new H264Decoder(); + + // NB: nothing that needs explicit teardown should be done + // before this point, since this can throw an exception + try { + this._display = new Display(this._canvas); + } catch (exc) { + Log.Error("Display exception: " + exc); + throw exc; + } + + this._keyboard = new Keyboard(this._canvas); + this._keyboard.onkeyevent = this._handleKeyEvent.bind(this); + this._remoteCapsLock = null; // Null indicates unknown or irrelevant + this._remoteNumLock = null; + + this._gestures = new GestureHandler(); + + this._sock = new Websock(); + this._sock.on('open', this._socketOpen.bind(this)); + this._sock.on('close', this._socketClose.bind(this)); + this._sock.on('message', this._handleMessage.bind(this)); + this._sock.on('error', this._socketError.bind(this)); + + this._expectedClientWidth = null; + this._expectedClientHeight = null; + this._resizeObserver = new ResizeObserver(this._eventHandlers.handleResize); + + // All prepared, kick off the connection + this._updateConnectionState('connecting'); + + Log.Debug("<< RFB.constructor"); + + // ===== PROPERTIES ===== + + this.dragViewport = false; + this.focusOnClick = true; + + this._viewOnly = false; + this._clipViewport = false; + this._clippingViewport = false; + this._scaleViewport = false; + this._resizeSession = false; + + this._showDotCursor = false; + + this._qualityLevel = 6; + this._compressionLevel = 2; + } + + // ===== PROPERTIES ===== + + get viewOnly() { return this._viewOnly; } + set viewOnly(viewOnly) { + this._viewOnly = viewOnly; + + if (this._rfbConnectionState === "connecting" || + this._rfbConnectionState === "connected") { + if (viewOnly) { + this._keyboard.ungrab(); + } else { + this._keyboard.grab(); + } + } + } + + get capabilities() { return this._capabilities; } + + get clippingViewport() { return this._clippingViewport; } + _setClippingViewport(on) { + if (on === this._clippingViewport) { + return; + } + this._clippingViewport = on; + this.dispatchEvent(new CustomEvent("clippingviewport", + { detail: this._clippingViewport })); + } + + get touchButton() { return 0; } + set touchButton(button) { Log.Warn("Using old API!"); } + + get clipViewport() { return this._clipViewport; } + set clipViewport(viewport) { + this._clipViewport = viewport; + this._updateClip(); + } + + get scaleViewport() { return this._scaleViewport; } + set scaleViewport(scale) { + this._scaleViewport = scale; + // Scaling trumps clipping, so we may need to adjust + // clipping when enabling or disabling scaling + if (scale && this._clipViewport) { + this._updateClip(); + } + this._updateScale(); + if (!scale && this._clipViewport) { + this._updateClip(); + } + } + + get resizeSession() { return this._resizeSession; } + set resizeSession(resize) { + this._resizeSession = resize; + if (resize) { + this._requestRemoteResize(); + } + } + + get showDotCursor() { return this._showDotCursor; } + set showDotCursor(show) { + this._showDotCursor = show; + this._refreshCursor(); + } + + get background() { return this._screen.style.background; } + set background(cssValue) { this._screen.style.background = cssValue; } + + get qualityLevel() { + return this._qualityLevel; + } + set qualityLevel(qualityLevel) { + if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { + Log.Error("qualityLevel must be an integer between 0 and 9"); + return; + } + + if (this._qualityLevel === qualityLevel) { + return; + } + + this._qualityLevel = qualityLevel; + + if (this._rfbConnectionState === 'connected') { + this._sendEncodings(); + } + } + + get compressionLevel() { + return this._compressionLevel; + } + set compressionLevel(compressionLevel) { + if (!Number.isInteger(compressionLevel) || compressionLevel < 0 || compressionLevel > 9) { + Log.Error("compressionLevel must be an integer between 0 and 9"); + return; + } + + if (this._compressionLevel === compressionLevel) { + return; + } + + this._compressionLevel = compressionLevel; + + if (this._rfbConnectionState === 'connected') { + this._sendEncodings(); + } + } + + // ===== PUBLIC METHODS ===== + + disconnect() { + this._updateConnectionState('disconnecting'); + this._sock.off('error'); + this._sock.off('message'); + this._sock.off('open'); + if (this._rfbRSAAESAuthenticationState !== null) { + this._rfbRSAAESAuthenticationState.disconnect(); + } + } + + approveServer() { + if (this._rfbRSAAESAuthenticationState !== null) { + this._rfbRSAAESAuthenticationState.approveServer(); + } + } + + sendCredentials(creds) { + this._rfbCredentials = creds; + this._resumeAuthentication(); + } + + sendCtrlAltDel() { + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } + Log.Info("Sending Ctrl-Alt-Del"); + + this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true); + this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true); + this.sendKey(KeyTable.XK_Delete, "Delete", true); + this.sendKey(KeyTable.XK_Delete, "Delete", false); + this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false); + this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false); + } + + machineShutdown() { + this._xvpOp(1, 2); + } + + machineReboot() { + this._xvpOp(1, 3); + } + + machineReset() { + this._xvpOp(1, 4); + } + + // Send a key press. If 'down' is not specified then send a down key + // followed by an up key. + sendKey(keysym, code, down) { + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } + + if (down === undefined) { + this.sendKey(keysym, code, true); + this.sendKey(keysym, code, false); + return; + } + + const scancode = XtScancode[code]; + + if (this._qemuExtKeyEventSupported && scancode) { + // 0 is NoSymbol + keysym = keysym || 0; + + Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode); + + RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode); + } else { + if (!keysym) { + return; + } + Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym); + RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0); + } + } + + focus(options) { + this._canvas.focus(options); + } + + blur() { + this._canvas.blur(); + } + + clipboardPasteFrom(text) { + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } + + if (this._clipboardServerCapabilitiesFormats[extendedClipboardFormatText] && + this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) { + + this._clipboardText = text; + RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]); + } else { + let length, i; + let data; + + length = 0; + // eslint-disable-next-line no-unused-vars + for (let codePoint of text) { + length++; + } + + data = new Uint8Array(length); + + i = 0; + for (let codePoint of text) { + let code = codePoint.codePointAt(0); + + /* Only ISO 8859-1 is supported */ + if (code > 0xff) { + code = 0x3f; // '?' + } + + data[i++] = code; + } + + RFB.messages.clientCutText(this._sock, data); + } + } + + getImageData() { + return this._display.getImageData(); + } + + toDataURL(type, encoderOptions) { + return this._display.toDataURL(type, encoderOptions); + } + + toBlob(callback, type, quality) { + return this._display.toBlob(callback, type, quality); + } + + // ===== PRIVATE METHODS ===== + + _connect() { + Log.Debug(">> RFB.connect"); + + if (this._url) { + Log.Info(`connecting to ${this._url}`); + this._sock.open(this._url, this._wsProtocols); + } else { + Log.Info(`attaching ${this._rawChannel} to Websock`); + this._sock.attach(this._rawChannel); + + if (this._sock.readyState === 'closed') { + throw Error("Cannot use already closed WebSocket/RTCDataChannel"); + } + + if (this._sock.readyState === 'open') { + // FIXME: _socketOpen() can in theory call _fail(), which + // isn't allowed this early, but I'm not sure that can + // happen without a bug messing up our state variables + this._socketOpen(); + } + } + + // Make our elements part of the page + this._target.appendChild(this._screen); + + this._gestures.attach(this._canvas); + + this._cursor.attach(this._canvas); + this._refreshCursor(); + + // Monitor size changes of the screen element + this._resizeObserver.observe(this._screen); + + // Always grab focus on some kind of click event + this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas); + this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas); + + // Mouse events + this._canvas.addEventListener('mousedown', this._eventHandlers.handleMouse); + this._canvas.addEventListener('mouseup', this._eventHandlers.handleMouse); + this._canvas.addEventListener('mousemove', this._eventHandlers.handleMouse); + // Prevent middle-click pasting (see handler for why we bind to document) + this._canvas.addEventListener('click', this._eventHandlers.handleMouse); + // preventDefault() on mousedown doesn't stop this event for some + // reason so we have to explicitly block it + this._canvas.addEventListener('contextmenu', this._eventHandlers.handleMouse); + + // Wheel events + this._canvas.addEventListener("wheel", this._eventHandlers.handleWheel); + + // Gesture events + this._canvas.addEventListener("gesturestart", this._eventHandlers.handleGesture); + this._canvas.addEventListener("gesturemove", this._eventHandlers.handleGesture); + this._canvas.addEventListener("gestureend", this._eventHandlers.handleGesture); + + Log.Debug("<< RFB.connect"); + } + + _disconnect() { + Log.Debug(">> RFB.disconnect"); + this._cursor.detach(); + this._canvas.removeEventListener("gesturestart", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("gesturemove", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("gestureend", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("wheel", this._eventHandlers.handleWheel); + this._canvas.removeEventListener('mousedown', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('mouseup', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('mousemove', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('click', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('contextmenu', this._eventHandlers.handleMouse); + this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas); + this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas); + this._resizeObserver.disconnect(); + this._keyboard.ungrab(); + this._gestures.detach(); + this._sock.close(); + try { + this._target.removeChild(this._screen); + } catch (e) { + if (e.name === 'NotFoundError') { + // Some cases where the initial connection fails + // can disconnect before the _screen is created + } else { + throw e; + } + } + clearTimeout(this._resizeTimeout); + clearTimeout(this._mouseMoveTimer); + Log.Debug("<< RFB.disconnect"); + } + + _socketOpen() { + if ((this._rfbConnectionState === 'connecting') && + (this._rfbInitState === '')) { + this._rfbInitState = 'ProtocolVersion'; + Log.Debug("Starting VNC handshake"); + } else { + this._fail("Unexpected server connection while " + + this._rfbConnectionState); + } + } + + _socketClose(e) { + Log.Debug("WebSocket on-close event"); + let msg = ""; + if (e.code) { + msg = "(code: " + e.code; + if (e.reason) { + msg += ", reason: " + e.reason; + } + msg += ")"; + } + switch (this._rfbConnectionState) { + case 'connecting': + this._fail("Connection closed " + msg); + break; + case 'connected': + // Handle disconnects that were initiated server-side + this._updateConnectionState('disconnecting'); + this._updateConnectionState('disconnected'); + break; + case 'disconnecting': + // Normal disconnection path + this._updateConnectionState('disconnected'); + break; + case 'disconnected': + this._fail("Unexpected server disconnect " + + "when already disconnected " + msg); + break; + default: + this._fail("Unexpected server disconnect before connecting " + + msg); + break; + } + this._sock.off('close'); + // Delete reference to raw channel to allow cleanup. + this._rawChannel = null; + } + + _socketError(e) { + Log.Warn("WebSocket on-error event"); + } + + _focusCanvas(event) { + if (!this.focusOnClick) { + return; + } + + this.focus({ preventScroll: true }); + } + + _setDesktopName(name) { + this._fbName = name; + this.dispatchEvent(new CustomEvent( + "desktopname", + { detail: { name: this._fbName } })); + } + + _saveExpectedClientSize() { + this._expectedClientWidth = this._screen.clientWidth; + this._expectedClientHeight = this._screen.clientHeight; + } + + _currentClientSize() { + return [this._screen.clientWidth, this._screen.clientHeight]; + } + + _clientHasExpectedSize() { + const [currentWidth, currentHeight] = this._currentClientSize(); + return currentWidth == this._expectedClientWidth && + currentHeight == this._expectedClientHeight; + } + + // Handle browser window resizes + _handleResize() { + // Don't change anything if the client size is already as expected + if (this._clientHasExpectedSize()) { + return; + } + // If the window resized then our screen element might have + // as well. Update the viewport dimensions. + window.requestAnimationFrame(() => { + this._updateClip(); + this._updateScale(); + this._saveExpectedClientSize(); + }); + + // Request changing the resolution of the remote display to + // the size of the local browser viewport. + this._requestRemoteResize(); + } + + // Update state of clipping in Display object, and make sure the + // configured viewport matches the current screen size + _updateClip() { + const curClip = this._display.clipViewport; + let newClip = this._clipViewport; + + if (this._scaleViewport) { + // Disable viewport clipping if we are scaling + newClip = false; + } + + if (curClip !== newClip) { + this._display.clipViewport = newClip; + } + + if (newClip) { + // When clipping is enabled, the screen is limited to + // the size of the container. + const size = this._screenSize(); + this._display.viewportChangeSize(size.w, size.h); + this._fixScrollbars(); + this._setClippingViewport(size.w < this._display.width || + size.h < this._display.height); + } else { + this._setClippingViewport(false); + } + + // When changing clipping we might show or hide scrollbars. + // This causes the expected client dimensions to change. + if (curClip !== newClip) { + this._saveExpectedClientSize(); + } + } + + _updateScale() { + if (!this._scaleViewport) { + this._display.scale = 1.0; + } else { + const size = this._screenSize(); + this._display.autoscale(size.w, size.h); + } + this._fixScrollbars(); + } + + // Requests a change of remote desktop size. This message is an extension + // and may only be sent if we have received an ExtendedDesktopSize message + _requestRemoteResize() { + if (!this._resizeSession) { + return; + } + if (this._viewOnly) { + return; + } + if (!this._supportsSetDesktopSize) { + return; + } + + // Rate limit to one pending resize at a time + if (this._pendingRemoteResize) { + return; + } + + // And no more than once every 100ms + if ((Date.now() - this._lastResize) < 100) { + clearTimeout(this._resizeTimeout); + this._resizeTimeout = setTimeout(this._requestRemoteResize.bind(this), + 100 - (Date.now() - this._lastResize)); + return; + } + this._resizeTimeout = null; + + const size = this._screenSize(); + + // Do we actually change anything? + if (size.w === this._fbWidth && size.h === this._fbHeight) { + return; + } + + this._pendingRemoteResize = true; + this._lastResize = Date.now(); + RFB.messages.setDesktopSize(this._sock, + Math.floor(size.w), Math.floor(size.h), + this._screenID, this._screenFlags); + + Log.Debug('Requested new desktop size: ' + + size.w + 'x' + size.h); + } + + // Gets the the size of the available screen + _screenSize() { + let r = this._screen.getBoundingClientRect(); + return { w: r.width, h: r.height }; + } + + _fixScrollbars() { + // This is a hack because Safari on macOS screws up the calculation + // for when scrollbars are needed. We get scrollbars when making the + // browser smaller, despite remote resize being enabled. So to fix it + // we temporarily toggle them off and on. + const orig = this._screen.style.overflow; + this._screen.style.overflow = 'hidden'; + // Force Safari to recalculate the layout by asking for + // an element's dimensions + this._screen.getBoundingClientRect(); + this._screen.style.overflow = orig; + } + + /* + * Connection states: + * connecting + * connected + * disconnecting + * disconnected - permanent state + */ + _updateConnectionState(state) { + const oldstate = this._rfbConnectionState; + + if (state === oldstate) { + Log.Debug("Already in state '" + state + "', ignoring"); + return; + } + + // The 'disconnected' state is permanent for each RFB object + if (oldstate === 'disconnected') { + Log.Error("Tried changing state of a disconnected RFB object"); + return; + } + + // Ensure proper transitions before doing anything + switch (state) { + case 'connected': + if (oldstate !== 'connecting') { + Log.Error("Bad transition to connected state, " + + "previous connection state: " + oldstate); + return; + } + break; + + case 'disconnected': + if (oldstate !== 'disconnecting') { + Log.Error("Bad transition to disconnected state, " + + "previous connection state: " + oldstate); + return; + } + break; + + case 'connecting': + if (oldstate !== '') { + Log.Error("Bad transition to connecting state, " + + "previous connection state: " + oldstate); + return; + } + break; + + case 'disconnecting': + if (oldstate !== 'connected' && oldstate !== 'connecting') { + Log.Error("Bad transition to disconnecting state, " + + "previous connection state: " + oldstate); + return; + } + break; + + default: + Log.Error("Unknown connection state: " + state); + return; + } + + // State change actions + + this._rfbConnectionState = state; + + Log.Debug("New state '" + state + "', was '" + oldstate + "'."); + + if (this._disconnTimer && state !== 'disconnecting') { + Log.Debug("Clearing disconnect timer"); + clearTimeout(this._disconnTimer); + this._disconnTimer = null; + + // make sure we don't get a double event + this._sock.off('close'); + } + + switch (state) { + case 'connecting': + this._connect(); + break; + + case 'connected': + this.dispatchEvent(new CustomEvent("connect", { detail: {} })); + break; + + case 'disconnecting': + this._disconnect(); + + this._disconnTimer = setTimeout(() => { + Log.Error("Disconnection timed out."); + this._updateConnectionState('disconnected'); + }, DISCONNECT_TIMEOUT * 1000); + break; + + case 'disconnected': + this.dispatchEvent(new CustomEvent( + "disconnect", { detail: + { clean: this._rfbCleanDisconnect } })); + break; + } + } + + /* Print errors and disconnect + * + * The parameter 'details' is used for information that + * should be logged but not sent to the user interface. + */ + _fail(details) { + switch (this._rfbConnectionState) { + case 'disconnecting': + Log.Error("Failed when disconnecting: " + details); + break; + case 'connected': + Log.Error("Failed while connected: " + details); + break; + case 'connecting': + Log.Error("Failed when connecting: " + details); + break; + default: + Log.Error("RFB failure: " + details); + break; + } + this._rfbCleanDisconnect = false; //This is sent to the UI + + // Transition to disconnected without waiting for socket to close + this._updateConnectionState('disconnecting'); + this._updateConnectionState('disconnected'); + + return false; + } + + _setCapability(cap, val) { + this._capabilities[cap] = val; + this.dispatchEvent(new CustomEvent("capabilities", + { detail: { capabilities: this._capabilities } })); + } + + _handleMessage() { + if (this._sock.rQwait("message", 1)) { + Log.Warn("handleMessage called on an empty receive queue"); + return; + } + + switch (this._rfbConnectionState) { + case 'disconnected': + Log.Error("Got data while disconnected"); + break; + case 'connected': + while (true) { + if (this._flushing) { + break; + } + if (!this._normalMsg()) { + break; + } + if (this._sock.rQwait("message", 1)) { + break; + } + } + break; + case 'connecting': + while (this._rfbConnectionState === 'connecting') { + if (!this._initMsg()) { + break; + } + } + break; + default: + Log.Error("Got data while in an invalid state"); + break; + } + } + + _handleKeyEvent(keysym, code, down, numlock, capslock) { + // If remote state of capslock is known, and it doesn't match the local led state of + // the keyboard, we send a capslock keypress first to bring it into sync. + // If we just pressed CapsLock, or we toggled it remotely due to it being out of sync + // we clear the remote state so that we don't send duplicate or spurious fixes, + // since it may take some time to receive the new remote CapsLock state. + if (code == 'CapsLock' && down) { + this._remoteCapsLock = null; + } + if (this._remoteCapsLock !== null && capslock !== null && this._remoteCapsLock !== capslock && down) { + Log.Debug("Fixing remote caps lock"); + + this.sendKey(KeyTable.XK_Caps_Lock, 'CapsLock', true); + this.sendKey(KeyTable.XK_Caps_Lock, 'CapsLock', false); + // We clear the remote capsLock state when we do this to prevent issues with doing this twice + // before we receive an update of the the remote state. + this._remoteCapsLock = null; + } + + // Logic for numlock is exactly the same. + if (code == 'NumLock' && down) { + this._remoteNumLock = null; + } + if (this._remoteNumLock !== null && numlock !== null && this._remoteNumLock !== numlock && down) { + Log.Debug("Fixing remote num lock"); + this.sendKey(KeyTable.XK_Num_Lock, 'NumLock', true); + this.sendKey(KeyTable.XK_Num_Lock, 'NumLock', false); + this._remoteNumLock = null; + } + this.sendKey(keysym, code, down); + } + + static _convertButtonMask(buttons) { + /* The bits in MouseEvent.buttons property correspond + * to the following mouse buttons: + * 0: Left + * 1: Right + * 2: Middle + * 3: Back + * 4: Forward + * + * These bits needs to be converted to what they are defined as + * in the RFB protocol. + */ + + const buttonMaskMap = { + 0: 1 << 0, // Left + 1: 1 << 2, // Right + 2: 1 << 1, // Middle + 3: 1 << 7, // Back + 4: 1 << 8, // Forward + }; + + let bmask = 0; + for (let i = 0; i < 5; i++) { + if (buttons & (1 << i)) { + bmask |= buttonMaskMap[i]; + } + } + return bmask; + } + + _handleMouse(ev) { + /* + * We don't check connection status or viewOnly here as the + * mouse events might be used to control the viewport + */ + + if (ev.type === 'click') { + /* + * Note: This is only needed for the 'click' event as it fails + * to fire properly for the target element so we have + * to listen on the document element instead. + */ + if (ev.target !== this._canvas) { + return; + } + } + + // FIXME: if we're in view-only and not dragging, + // should we stop events? + ev.stopPropagation(); + ev.preventDefault(); + + if ((ev.type === 'click') || (ev.type === 'contextmenu')) { + return; + } + + let pos = clientToElement(ev.clientX, ev.clientY, + this._canvas); + + let bmask = RFB._convertButtonMask(ev.buttons); + + let down = ev.type == 'mousedown'; + switch (ev.type) { + case 'mousedown': + case 'mouseup': + if (this.dragViewport) { + if (down && !this._viewportDragging) { + this._viewportDragging = true; + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + this._viewportHasMoved = false; + + this._flushMouseMoveTimer(pos.x, pos.y); + + // Skip sending mouse events, instead save the current + // mouse mask so we can send it later. + this._mouseButtonMask = bmask; + break; + } else { + this._viewportDragging = false; + + // If we actually performed a drag then we are done + // here and should not send any mouse events + if (this._viewportHasMoved) { + this._mouseButtonMask = bmask; + break; + } + // Otherwise we treat this as a mouse click event. + // Send the previously saved button mask, followed + // by the current button mask at the end of this + // function. + this._sendMouse(pos.x, pos.y, this._mouseButtonMask); + } + } + if (down) { + setCapture(this._canvas); + } + this._handleMouseButton(pos.x, pos.y, bmask); + break; + case 'mousemove': + if (this._viewportDragging) { + const deltaX = this._viewportDragPos.x - pos.x; + const deltaY = this._viewportDragPos.y - pos.y; + + if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold || + Math.abs(deltaY) > dragThreshold)) { + this._viewportHasMoved = true; + + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + this._display.viewportChangePos(deltaX, deltaY); + } + + // Skip sending mouse events + break; + } + this._handleMouseMove(pos.x, pos.y); + break; + } + } + + _handleMouseButton(x, y, bmask) { + // Flush waiting move event first + this._flushMouseMoveTimer(x, y); + + this._mouseButtonMask = bmask; + this._sendMouse(x, y, this._mouseButtonMask); + } + + _handleMouseMove(x, y) { + this._mousePos = { 'x': x, 'y': y }; + + // Limit many mouse move events to one every MOUSE_MOVE_DELAY ms + if (this._mouseMoveTimer == null) { + + const timeSinceLastMove = Date.now() - this._mouseLastMoveTime; + if (timeSinceLastMove > MOUSE_MOVE_DELAY) { + this._sendMouse(x, y, this._mouseButtonMask); + this._mouseLastMoveTime = Date.now(); + } else { + // Too soon since the latest move, wait the remaining time + this._mouseMoveTimer = setTimeout(() => { + this._handleDelayedMouseMove(); + }, MOUSE_MOVE_DELAY - timeSinceLastMove); + } + } + } + + _handleDelayedMouseMove() { + this._mouseMoveTimer = null; + this._sendMouse(this._mousePos.x, this._mousePos.y, + this._mouseButtonMask); + this._mouseLastMoveTime = Date.now(); + } + + _sendMouse(x, y, mask) { + if (this._rfbConnectionState !== 'connected') { return; } + if (this._viewOnly) { return; } // View only, skip mouse events + + // Highest bit in mask is never sent to the server + if (mask & 0x8000) { + throw new Error("Illegal mouse button mask (mask: " + mask + ")"); + } + + let extendedMouseButtons = mask & 0x7f80; + + if (this._extendedPointerEventSupported && extendedMouseButtons) { + RFB.messages.extendedPointerEvent(this._sock, this._display.absX(x), + this._display.absY(y), mask); + } else { + RFB.messages.pointerEvent(this._sock, this._display.absX(x), + this._display.absY(y), mask); + } + } + + _handleWheel(ev) { + if (this._rfbConnectionState !== 'connected') { return; } + if (this._viewOnly) { return; } // View only, skip mouse events + + ev.stopPropagation(); + ev.preventDefault(); + + let pos = clientToElement(ev.clientX, ev.clientY, + this._canvas); + + let bmask = RFB._convertButtonMask(ev.buttons); + let dX = ev.deltaX; + let dY = ev.deltaY; + + // Pixel units unless it's non-zero. + // Note that if deltamode is line or page won't matter since we aren't + // sending the mouse wheel delta to the server anyway. + // The difference between pixel and line can be important however since + // we have a threshold that can be smaller than the line height. + if (ev.deltaMode !== 0) { + dX *= WHEEL_LINE_HEIGHT; + dY *= WHEEL_LINE_HEIGHT; + } + + // Mouse wheel events are sent in steps over VNC. This means that the VNC + // protocol can't handle a wheel event with specific distance or speed. + // Therefor, if we get a lot of small mouse wheel events we combine them. + this._accumulatedWheelDeltaX += dX; + this._accumulatedWheelDeltaY += dY; + + + // Generate a mouse wheel step event when the accumulated delta + // for one of the axes is large enough. + if (Math.abs(this._accumulatedWheelDeltaX) >= WHEEL_STEP) { + if (this._accumulatedWheelDeltaX < 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 5); + this._handleMouseButton(pos.x, pos.y, bmask); + } else if (this._accumulatedWheelDeltaX > 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 6); + this._handleMouseButton(pos.x, pos.y, bmask); + } + + this._accumulatedWheelDeltaX = 0; + } + if (Math.abs(this._accumulatedWheelDeltaY) >= WHEEL_STEP) { + if (this._accumulatedWheelDeltaY < 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 3); + this._handleMouseButton(pos.x, pos.y, bmask); + } else if (this._accumulatedWheelDeltaY > 0) { + this._handleMouseButton(pos.x, pos.y, bmask | 1 << 4); + this._handleMouseButton(pos.x, pos.y, bmask); + } + + this._accumulatedWheelDeltaY = 0; + } + } + + _fakeMouseMove(ev, elementX, elementY) { + this._handleMouseMove(elementX, elementY); + this._cursor.move(ev.detail.clientX, ev.detail.clientY); + } + + _handleTapEvent(ev, bmask) { + let pos = clientToElement(ev.detail.clientX, ev.detail.clientY, + this._canvas); + + // If the user quickly taps multiple times we assume they meant to + // hit the same spot, so slightly adjust coordinates + + if ((this._gestureLastTapTime !== null) && + ((Date.now() - this._gestureLastTapTime) < DOUBLE_TAP_TIMEOUT) && + (this._gestureFirstDoubleTapEv.detail.type === ev.detail.type)) { + let dx = this._gestureFirstDoubleTapEv.detail.clientX - ev.detail.clientX; + let dy = this._gestureFirstDoubleTapEv.detail.clientY - ev.detail.clientY; + let distance = Math.hypot(dx, dy); + + if (distance < DOUBLE_TAP_THRESHOLD) { + pos = clientToElement(this._gestureFirstDoubleTapEv.detail.clientX, + this._gestureFirstDoubleTapEv.detail.clientY, + this._canvas); + } else { + this._gestureFirstDoubleTapEv = ev; + } + } else { + this._gestureFirstDoubleTapEv = ev; + } + this._gestureLastTapTime = Date.now(); + + this._fakeMouseMove(this._gestureFirstDoubleTapEv, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, bmask); + this._handleMouseButton(pos.x, pos.y, 0x0); + } + + _handleGesture(ev) { + let magnitude; + + let pos = clientToElement(ev.detail.clientX, ev.detail.clientY, + this._canvas); + switch (ev.type) { + case 'gesturestart': + switch (ev.detail.type) { + case 'onetap': + this._handleTapEvent(ev, 0x1); + break; + case 'twotap': + this._handleTapEvent(ev, 0x4); + break; + case 'threetap': + this._handleTapEvent(ev, 0x2); + break; + case 'drag': + if (this.dragViewport) { + this._viewportHasMoved = false; + this._viewportDragging = true; + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x1); + } + break; + case 'longpress': + if (this.dragViewport) { + // If dragViewport is true, we need to wait to see + // if we have dragged outside the threshold before + // sending any events to the server. + this._viewportHasMoved = false; + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x4); + } + break; + case 'twodrag': + this._gestureLastMagnitudeX = ev.detail.magnitudeX; + this._gestureLastMagnitudeY = ev.detail.magnitudeY; + this._fakeMouseMove(ev, pos.x, pos.y); + break; + case 'pinch': + this._gestureLastMagnitudeX = Math.hypot(ev.detail.magnitudeX, + ev.detail.magnitudeY); + this._fakeMouseMove(ev, pos.x, pos.y); + break; + } + break; + + case 'gesturemove': + switch (ev.detail.type) { + case 'onetap': + case 'twotap': + case 'threetap': + break; + case 'drag': + case 'longpress': + if (this.dragViewport) { + this._viewportDragging = true; + const deltaX = this._viewportDragPos.x - pos.x; + const deltaY = this._viewportDragPos.y - pos.y; + + if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold || + Math.abs(deltaY) > dragThreshold)) { + this._viewportHasMoved = true; + + this._viewportDragPos = {'x': pos.x, 'y': pos.y}; + this._display.viewportChangePos(deltaX, deltaY); + } + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + } + break; + case 'twodrag': + // Always scroll in the same position. + // We don't know if the mouse was moved so we need to move it + // every update. + this._fakeMouseMove(ev, pos.x, pos.y); + while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) > GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x8); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeY += GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) < -GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x10); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeY -= GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) > GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x20); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX += GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) < -GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, 0x40); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX -= GESTURE_SCRLSENS; + } + break; + case 'pinch': + // Always scroll in the same position. + // We don't know if the mouse was moved so we need to move it + // every update. + this._fakeMouseMove(ev, pos.x, pos.y); + magnitude = Math.hypot(ev.detail.magnitudeX, ev.detail.magnitudeY); + if (Math.abs(magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) { + this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); + while ((magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) { + this._handleMouseButton(pos.x, pos.y, 0x8); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX += GESTURE_ZOOMSENS; + } + while ((magnitude - this._gestureLastMagnitudeX) < -GESTURE_ZOOMSENS) { + this._handleMouseButton(pos.x, pos.y, 0x10); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._gestureLastMagnitudeX -= GESTURE_ZOOMSENS; + } + } + this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", false); + break; + } + break; + + case 'gestureend': + switch (ev.detail.type) { + case 'onetap': + case 'twotap': + case 'threetap': + case 'pinch': + case 'twodrag': + break; + case 'drag': + if (this.dragViewport) { + this._viewportDragging = false; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x0); + } + break; + case 'longpress': + if (this._viewportHasMoved) { + // We don't want to send any events if we have moved + // our viewport + break; + } + + if (this.dragViewport && !this._viewportHasMoved) { + this._fakeMouseMove(ev, pos.x, pos.y); + // If dragViewport is true, we need to wait to see + // if we have dragged outside the threshold before + // sending any events to the server. + this._handleMouseButton(pos.x, pos.y, 0x4); + this._handleMouseButton(pos.x, pos.y, 0x0); + this._viewportDragging = false; + } else { + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, 0x0); + } + break; + } + break; + } + } + + _flushMouseMoveTimer(x, y) { + if (this._mouseMoveTimer !== null) { + clearTimeout(this._mouseMoveTimer); + this._mouseMoveTimer = null; + this._sendMouse(x, y, this._mouseButtonMask); + } + } + + // Message handlers + + _negotiateProtocolVersion() { + if (this._sock.rQwait("version", 12)) { + return false; + } + + const sversion = this._sock.rQshiftStr(12).substr(4, 7); + Log.Info("Server ProtocolVersion: " + sversion); + let isRepeater = 0; + switch (sversion) { + case "000.000": // UltraVNC repeater + isRepeater = 1; + break; + case "003.003": + case "003.006": // UltraVNC + this._rfbVersion = 3.3; + break; + case "003.007": + this._rfbVersion = 3.7; + break; + case "003.008": + case "003.889": // Apple Remote Desktop + case "004.000": // Intel AMT KVM + case "004.001": // RealVNC 4.6 + case "005.000": // RealVNC 5.3 + this._rfbVersion = 3.8; + break; + default: + return this._fail("Invalid server version " + sversion); + } + + if (isRepeater) { + let repeaterID = "ID:" + this._repeaterID; + while (repeaterID.length < 250) { + repeaterID += "\0"; + } + this._sock.sQpushString(repeaterID); + this._sock.flush(); + return true; + } + + if (this._rfbVersion > this._rfbMaxVersion) { + this._rfbVersion = this._rfbMaxVersion; + } + + const cversion = "00" + parseInt(this._rfbVersion, 10) + + ".00" + ((this._rfbVersion * 10) % 10); + this._sock.sQpushString("RFB " + cversion + "\n"); + this._sock.flush(); + Log.Debug('Sent ProtocolVersion: ' + cversion); + + this._rfbInitState = 'Security'; + } + + _isSupportedSecurityType(type) { + const clientTypes = [ + securityTypeNone, + securityTypeVNCAuth, + securityTypeRA2ne, + securityTypeTight, + securityTypeVeNCrypt, + securityTypeXVP, + securityTypeARD, + securityTypeMSLogonII, + securityTypePlain, + ]; + + return clientTypes.includes(type); + } + + _negotiateSecurity() { + if (this._rfbVersion >= 3.7) { + // Server sends supported list, client decides + const numTypes = this._sock.rQshift8(); + if (this._sock.rQwait("security type", numTypes, 1)) { return false; } + + if (numTypes === 0) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "no security types"; + this._securityStatus = 1; + return true; + } + + const types = this._sock.rQshiftBytes(numTypes); + Log.Debug("Server security types: " + types); + + // Look for a matching security type in the order that the + // server prefers + this._rfbAuthScheme = -1; + for (let type of types) { + if (this._isSupportedSecurityType(type)) { + this._rfbAuthScheme = type; + break; + } + } + + if (this._rfbAuthScheme === -1) { + return this._fail("Unsupported security types (types: " + types + ")"); + } + + this._sock.sQpush8(this._rfbAuthScheme); + this._sock.flush(); + } else { + // Server decides + if (this._sock.rQwait("security scheme", 4)) { return false; } + this._rfbAuthScheme = this._sock.rQshift32(); + + if (this._rfbAuthScheme == 0) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "authentication scheme"; + this._securityStatus = 1; + return true; + } + } + + this._rfbInitState = 'Authentication'; + Log.Debug('Authenticating using scheme: ' + this._rfbAuthScheme); + + return true; + } + + _handleSecurityReason() { + if (this._sock.rQwait("reason length", 4)) { + return false; + } + const strlen = this._sock.rQshift32(); + let reason = ""; + + if (strlen > 0) { + if (this._sock.rQwait("reason", strlen, 4)) { return false; } + reason = this._sock.rQshiftStr(strlen); + } + + if (reason !== "") { + this.dispatchEvent(new CustomEvent( + "securityfailure", + { detail: { status: this._securityStatus, + reason: reason } })); + + return this._fail("Security negotiation failed on " + + this._securityContext + + " (reason: " + reason + ")"); + } else { + this.dispatchEvent(new CustomEvent( + "securityfailure", + { detail: { status: this._securityStatus } })); + + return this._fail("Security negotiation failed on " + + this._securityContext); + } + } + + // authentication + _negotiateXvpAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined || + this._rfbCredentials.target === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password", "target"] } })); + return false; + } + + this._sock.sQpush8(this._rfbCredentials.username.length); + this._sock.sQpush8(this._rfbCredentials.target.length); + this._sock.sQpushString(this._rfbCredentials.username); + this._sock.sQpushString(this._rfbCredentials.target); + + this._sock.flush(); + + this._rfbAuthScheme = securityTypeVNCAuth; + + return this._negotiateAuthentication(); + } + + // VeNCrypt authentication, currently only supports version 0.2 and only Plain subtype + _negotiateVeNCryptAuth() { + + // waiting for VeNCrypt version + if (this._rfbVeNCryptState == 0) { + if (this._sock.rQwait("vencrypt version", 2)) { return false; } + + const major = this._sock.rQshift8(); + const minor = this._sock.rQshift8(); + + if (!(major == 0 && minor == 2)) { + return this._fail("Unsupported VeNCrypt version " + major + "." + minor); + } + + this._sock.sQpush8(0); + this._sock.sQpush8(2); + this._sock.flush(); + this._rfbVeNCryptState = 1; + } + + // waiting for ACK + if (this._rfbVeNCryptState == 1) { + if (this._sock.rQwait("vencrypt ack", 1)) { return false; } + + const res = this._sock.rQshift8(); + + if (res != 0) { + return this._fail("VeNCrypt failure " + res); + } + + this._rfbVeNCryptState = 2; + } + // must fall through here (i.e. no "else if"), beacause we may have already received + // the subtypes length and won't be called again + + if (this._rfbVeNCryptState == 2) { // waiting for subtypes length + if (this._sock.rQwait("vencrypt subtypes length", 1)) { return false; } + + const subtypesLength = this._sock.rQshift8(); + if (subtypesLength < 1) { + return this._fail("VeNCrypt subtypes empty"); + } + + this._rfbVeNCryptSubtypesLength = subtypesLength; + this._rfbVeNCryptState = 3; + } + + // waiting for subtypes list + if (this._rfbVeNCryptState == 3) { + if (this._sock.rQwait("vencrypt subtypes", 4 * this._rfbVeNCryptSubtypesLength)) { return false; } + + const subtypes = []; + for (let i = 0; i < this._rfbVeNCryptSubtypesLength; i++) { + subtypes.push(this._sock.rQshift32()); + } + + // Look for a matching security type in the order that the + // server prefers + this._rfbAuthScheme = -1; + for (let type of subtypes) { + // Avoid getting in to a loop + if (type === securityTypeVeNCrypt) { + continue; + } + + if (this._isSupportedSecurityType(type)) { + this._rfbAuthScheme = type; + break; + } + } + + if (this._rfbAuthScheme === -1) { + return this._fail("Unsupported security types (types: " + subtypes + ")"); + } + + this._sock.sQpush32(this._rfbAuthScheme); + this._sock.flush(); + + this._rfbVeNCryptState = 4; + return true; + } + } + + _negotiatePlainAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + const user = encodeUTF8(this._rfbCredentials.username); + const pass = encodeUTF8(this._rfbCredentials.password); + + this._sock.sQpush32(user.length); + this._sock.sQpush32(pass.length); + this._sock.sQpushString(user); + this._sock.sQpushString(pass); + this._sock.flush(); + + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateStdVNCAuth() { + if (this._sock.rQwait("auth challenge", 16)) { return false; } + + if (this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["password"] } })); + return false; + } + + // TODO(directxman12): make genDES not require an Array + const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16)); + const response = RFB.genDES(this._rfbCredentials.password, challenge); + this._sock.sQpushBytes(response); + this._sock.flush(); + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateARDAuth() { + + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + if (this._rfbCredentials.ardPublicKey != undefined && + this._rfbCredentials.ardCredentials != undefined) { + // if the async web crypto is done return the results + this._sock.sQpushBytes(this._rfbCredentials.ardCredentials); + this._sock.sQpushBytes(this._rfbCredentials.ardPublicKey); + this._sock.flush(); + this._rfbCredentials.ardCredentials = null; + this._rfbCredentials.ardPublicKey = null; + this._rfbInitState = "SecurityResult"; + return true; + } + + if (this._sock.rQwait("read ard", 4)) { return false; } + + let generator = this._sock.rQshiftBytes(2); // DH base generator value + + let keyLength = this._sock.rQshift16(); + + if (this._sock.rQwait("read ard keylength", keyLength*2, 4)) { return false; } + + // read the server values + let prime = this._sock.rQshiftBytes(keyLength); // predetermined prime modulus + let serverPublicKey = this._sock.rQshiftBytes(keyLength); // other party's public key + + let clientKey = legacyCrypto.generateKey( + { name: "DH", g: generator, p: prime }, false, ["deriveBits"]); + this._negotiateARDAuthAsync(keyLength, serverPublicKey, clientKey); + + return false; + } + + async _negotiateARDAuthAsync(keyLength, serverPublicKey, clientKey) { + const clientPublicKey = legacyCrypto.exportKey("raw", clientKey.publicKey); + const sharedKey = legacyCrypto.deriveBits( + { name: "DH", public: serverPublicKey }, clientKey.privateKey, keyLength * 8); + + const username = encodeUTF8(this._rfbCredentials.username).substring(0, 63); + const password = encodeUTF8(this._rfbCredentials.password).substring(0, 63); + + const credentials = window.crypto.getRandomValues(new Uint8Array(128)); + for (let i = 0; i < username.length; i++) { + credentials[i] = username.charCodeAt(i); + } + credentials[username.length] = 0; + for (let i = 0; i < password.length; i++) { + credentials[64 + i] = password.charCodeAt(i); + } + credentials[64 + password.length] = 0; + + const key = await legacyCrypto.digest("MD5", sharedKey); + const cipher = await legacyCrypto.importKey( + "raw", key, { name: "AES-ECB" }, false, ["encrypt"]); + const encrypted = await legacyCrypto.encrypt({ name: "AES-ECB" }, cipher, credentials); + + this._rfbCredentials.ardCredentials = encrypted; + this._rfbCredentials.ardPublicKey = clientPublicKey; + + this._resumeAuthentication(); + } + + _negotiateTightUnixAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + this._sock.sQpush32(this._rfbCredentials.username.length); + this._sock.sQpush32(this._rfbCredentials.password.length); + this._sock.sQpushString(this._rfbCredentials.username); + this._sock.sQpushString(this._rfbCredentials.password); + this._sock.flush(); + + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateTightTunnels(numTunnels) { + const clientSupportedTunnelTypes = { + 0: { vendor: 'TGHT', signature: 'NOTUNNEL' } + }; + const serverSupportedTunnelTypes = {}; + // receive tunnel capabilities + for (let i = 0; i < numTunnels; i++) { + const capCode = this._sock.rQshift32(); + const capVendor = this._sock.rQshiftStr(4); + const capSignature = this._sock.rQshiftStr(8); + serverSupportedTunnelTypes[capCode] = { vendor: capVendor, signature: capSignature }; + } + + Log.Debug("Server Tight tunnel types: " + serverSupportedTunnelTypes); + + // Siemens touch panels have a VNC server that supports NOTUNNEL, + // but forgets to advertise it. Try to detect such servers by + // looking for their custom tunnel type. + if (serverSupportedTunnelTypes[1] && + (serverSupportedTunnelTypes[1].vendor === "SICR") && + (serverSupportedTunnelTypes[1].signature === "SCHANNEL")) { + Log.Debug("Detected Siemens server. Assuming NOTUNNEL support."); + serverSupportedTunnelTypes[0] = { vendor: 'TGHT', signature: 'NOTUNNEL' }; + } + + // choose the notunnel type + if (serverSupportedTunnelTypes[0]) { + if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor || + serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) { + return this._fail("Client's tunnel type had the incorrect " + + "vendor or signature"); + } + Log.Debug("Selected tunnel type: " + clientSupportedTunnelTypes[0]); + this._sock.sQpush32(0); // use NOTUNNEL + this._sock.flush(); + return false; // wait until we receive the sub auth count to continue + } else { + return this._fail("Server wanted tunnels, but doesn't support " + + "the notunnel type"); + } + } + + _negotiateTightAuth() { + if (!this._rfbTightVNC) { // first pass, do the tunnel negotiation + if (this._sock.rQwait("num tunnels", 4)) { return false; } + const numTunnels = this._sock.rQshift32(); + if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; } + + this._rfbTightVNC = true; + + if (numTunnels > 0) { + this._negotiateTightTunnels(numTunnels); + return false; // wait until we receive the sub auth to continue + } + } + + // second pass, do the sub-auth negotiation + if (this._sock.rQwait("sub auth count", 4)) { return false; } + const subAuthCount = this._sock.rQshift32(); + if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected + this._rfbInitState = 'SecurityResult'; + return true; + } + + if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; } + + const clientSupportedTypes = { + 'STDVNOAUTH__': 1, + 'STDVVNCAUTH_': 2, + 'TGHTULGNAUTH': 129 + }; + + const serverSupportedTypes = []; + + for (let i = 0; i < subAuthCount; i++) { + this._sock.rQshift32(); // capNum + const capabilities = this._sock.rQshiftStr(12); + serverSupportedTypes.push(capabilities); + } + + Log.Debug("Server Tight authentication types: " + serverSupportedTypes); + + for (let authType in clientSupportedTypes) { + if (serverSupportedTypes.indexOf(authType) != -1) { + this._sock.sQpush32(clientSupportedTypes[authType]); + this._sock.flush(); + Log.Debug("Selected authentication type: " + authType); + + switch (authType) { + case 'STDVNOAUTH__': // no auth + this._rfbInitState = 'SecurityResult'; + return true; + case 'STDVVNCAUTH_': + this._rfbAuthScheme = securityTypeVNCAuth; + return true; + case 'TGHTULGNAUTH': + this._rfbAuthScheme = securityTypeUnixLogon; + return true; + default: + return this._fail("Unsupported tiny auth scheme " + + "(scheme: " + authType + ")"); + } + } + } + + return this._fail("No supported sub-auth types!"); + } + + _handleRSAAESCredentialsRequired(event) { + this.dispatchEvent(event); + } + + _handleRSAAESServerVerification(event) { + this.dispatchEvent(event); + } + + _negotiateRA2neAuth() { + if (this._rfbRSAAESAuthenticationState === null) { + this._rfbRSAAESAuthenticationState = new RSAAESAuthenticationState(this._sock, () => this._rfbCredentials); + this._rfbRSAAESAuthenticationState.addEventListener( + "serververification", this._eventHandlers.handleRSAAESServerVerification); + this._rfbRSAAESAuthenticationState.addEventListener( + "credentialsrequired", this._eventHandlers.handleRSAAESCredentialsRequired); + } + this._rfbRSAAESAuthenticationState.checkInternalEvents(); + if (!this._rfbRSAAESAuthenticationState.hasStarted) { + this._rfbRSAAESAuthenticationState.negotiateRA2neAuthAsync() + .catch((e) => { + if (e.message !== "disconnect normally") { + this._fail(e.message); + } + }) + .then(() => { + this._rfbInitState = "SecurityResult"; + return true; + }).finally(() => { + this._rfbRSAAESAuthenticationState.removeEventListener( + "serververification", this._eventHandlers.handleRSAAESServerVerification); + this._rfbRSAAESAuthenticationState.removeEventListener( + "credentialsrequired", this._eventHandlers.handleRSAAESCredentialsRequired); + this._rfbRSAAESAuthenticationState = null; + }); + } + return false; + } + + _negotiateMSLogonIIAuth() { + if (this._sock.rQwait("mslogonii dh param", 24)) { return false; } + + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + const g = this._sock.rQshiftBytes(8); + const p = this._sock.rQshiftBytes(8); + const A = this._sock.rQshiftBytes(8); + const dhKey = legacyCrypto.generateKey({ name: "DH", g: g, p: p }, true, ["deriveBits"]); + const B = legacyCrypto.exportKey("raw", dhKey.publicKey); + const secret = legacyCrypto.deriveBits({ name: "DH", public: A }, dhKey.privateKey, 64); + + const key = legacyCrypto.importKey("raw", secret, { name: "DES-CBC" }, false, ["encrypt"]); + const username = encodeUTF8(this._rfbCredentials.username).substring(0, 255); + const password = encodeUTF8(this._rfbCredentials.password).substring(0, 63); + let usernameBytes = new Uint8Array(256); + let passwordBytes = new Uint8Array(64); + window.crypto.getRandomValues(usernameBytes); + window.crypto.getRandomValues(passwordBytes); + for (let i = 0; i < username.length; i++) { + usernameBytes[i] = username.charCodeAt(i); + } + usernameBytes[username.length] = 0; + for (let i = 0; i < password.length; i++) { + passwordBytes[i] = password.charCodeAt(i); + } + passwordBytes[password.length] = 0; + usernameBytes = legacyCrypto.encrypt({ name: "DES-CBC", iv: secret }, key, usernameBytes); + passwordBytes = legacyCrypto.encrypt({ name: "DES-CBC", iv: secret }, key, passwordBytes); + this._sock.sQpushBytes(B); + this._sock.sQpushBytes(usernameBytes); + this._sock.sQpushBytes(passwordBytes); + this._sock.flush(); + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateAuthentication() { + switch (this._rfbAuthScheme) { + case securityTypeNone: + if (this._rfbVersion >= 3.8) { + this._rfbInitState = 'SecurityResult'; + } else { + this._rfbInitState = 'ClientInitialisation'; + } + return true; + + case securityTypeXVP: + return this._negotiateXvpAuth(); + + case securityTypeARD: + return this._negotiateARDAuth(); + + case securityTypeVNCAuth: + return this._negotiateStdVNCAuth(); + + case securityTypeTight: + return this._negotiateTightAuth(); + + case securityTypeVeNCrypt: + return this._negotiateVeNCryptAuth(); + + case securityTypePlain: + return this._negotiatePlainAuth(); + + case securityTypeUnixLogon: + return this._negotiateTightUnixAuth(); + + case securityTypeRA2ne: + return this._negotiateRA2neAuth(); + + case securityTypeMSLogonII: + return this._negotiateMSLogonIIAuth(); + + default: + return this._fail("Unsupported auth scheme (scheme: " + + this._rfbAuthScheme + ")"); + } + } + + _handleSecurityResult() { + if (this._sock.rQwait('VNC auth response ', 4)) { return false; } + + const status = this._sock.rQshift32(); + + if (status === 0) { // OK + this._rfbInitState = 'ClientInitialisation'; + Log.Debug('Authentication OK'); + return true; + } else { + if (this._rfbVersion >= 3.8) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "security result"; + this._securityStatus = status; + return true; + } else { + this.dispatchEvent(new CustomEvent( + "securityfailure", + { detail: { status: status } })); + + return this._fail("Security handshake failed"); + } + } + } + + _negotiateServerInit() { + if (this._sock.rQwait("server initialization", 24)) { return false; } + + /* Screen size */ + const width = this._sock.rQshift16(); + const height = this._sock.rQshift16(); + + /* PIXEL_FORMAT */ + const bpp = this._sock.rQshift8(); + const depth = this._sock.rQshift8(); + const bigEndian = this._sock.rQshift8(); + const trueColor = this._sock.rQshift8(); + + const redMax = this._sock.rQshift16(); + const greenMax = this._sock.rQshift16(); + const blueMax = this._sock.rQshift16(); + const redShift = this._sock.rQshift8(); + const greenShift = this._sock.rQshift8(); + const blueShift = this._sock.rQshift8(); + this._sock.rQskipBytes(3); // padding + + // NB(directxman12): we don't want to call any callbacks or print messages until + // *after* we're past the point where we could backtrack + + /* Connection name/title */ + const nameLength = this._sock.rQshift32(); + if (this._sock.rQwait('server init name', nameLength, 24)) { return false; } + let name = this._sock.rQshiftStr(nameLength); + name = decodeUTF8(name, true); + + if (this._rfbTightVNC) { + if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + nameLength)) { return false; } + // In TightVNC mode, ServerInit message is extended + const numServerMessages = this._sock.rQshift16(); + const numClientMessages = this._sock.rQshift16(); + const numEncodings = this._sock.rQshift16(); + this._sock.rQskipBytes(2); // padding + + const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16; + if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + nameLength)) { return false; } + + // we don't actually do anything with the capability information that TIGHT sends, + // so we just skip the all of this. + + // TIGHT server message capabilities + this._sock.rQskipBytes(16 * numServerMessages); + + // TIGHT client message capabilities + this._sock.rQskipBytes(16 * numClientMessages); + + // TIGHT encoding capabilities + this._sock.rQskipBytes(16 * numEncodings); + } + + // NB(directxman12): these are down here so that we don't run them multiple times + // if we backtrack + Log.Info("Screen: " + width + "x" + height + + ", bpp: " + bpp + ", depth: " + depth + + ", bigEndian: " + bigEndian + + ", trueColor: " + trueColor + + ", redMax: " + redMax + + ", greenMax: " + greenMax + + ", blueMax: " + blueMax + + ", redShift: " + redShift + + ", greenShift: " + greenShift + + ", blueShift: " + blueShift); + + // we're past the point where we could backtrack, so it's safe to call this + this._setDesktopName(name); + this._resize(width, height); + + if (!this._viewOnly) { this._keyboard.grab(); } + + this._fbDepth = 24; + + if (this._fbName === "Intel(r) AMT KVM") { + Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode."); + this._fbDepth = 8; + } + + RFB.messages.pixelFormat(this._sock, this._fbDepth, true); + this._sendEncodings(); + RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fbWidth, this._fbHeight); + + this._updateConnectionState('connected'); + return true; + } + + _sendEncodings() { + const encs = []; + + // In preference order + encs.push(encodings.encodingCopyRect); + // Only supported with full depth support + if (this._fbDepth == 24) { + if (supportsWebCodecsH264Decode) { + encs.push(encodings.encodingH264); + } + encs.push(encodings.encodingTight); + encs.push(encodings.encodingTightPNG); + encs.push(encodings.encodingZRLE); + encs.push(encodings.encodingJPEG); + encs.push(encodings.encodingHextile); + encs.push(encodings.encodingRRE); + encs.push(encodings.encodingZlib); + } + encs.push(encodings.encodingRaw); + + // Psuedo-encoding settings + encs.push(encodings.pseudoEncodingQualityLevel0 + this._qualityLevel); + encs.push(encodings.pseudoEncodingCompressLevel0 + this._compressionLevel); + + encs.push(encodings.pseudoEncodingDesktopSize); + encs.push(encodings.pseudoEncodingLastRect); + encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent); + encs.push(encodings.pseudoEncodingQEMULedEvent); + encs.push(encodings.pseudoEncodingExtendedDesktopSize); + encs.push(encodings.pseudoEncodingXvp); + encs.push(encodings.pseudoEncodingFence); + encs.push(encodings.pseudoEncodingContinuousUpdates); + encs.push(encodings.pseudoEncodingDesktopName); + encs.push(encodings.pseudoEncodingExtendedClipboard); + encs.push(encodings.pseudoEncodingExtendedMouseButtons); + + if (this._fbDepth == 24) { + encs.push(encodings.pseudoEncodingVMwareCursor); + encs.push(encodings.pseudoEncodingCursor); + } + + RFB.messages.clientEncodings(this._sock, encs); + } + + /* RFB protocol initialization states: + * ProtocolVersion + * Security + * Authentication + * SecurityResult + * ClientInitialization - not triggered by server message + * ServerInitialization + */ + _initMsg() { + switch (this._rfbInitState) { + case 'ProtocolVersion': + return this._negotiateProtocolVersion(); + + case 'Security': + return this._negotiateSecurity(); + + case 'Authentication': + return this._negotiateAuthentication(); + + case 'SecurityResult': + return this._handleSecurityResult(); + + case 'SecurityReason': + return this._handleSecurityReason(); + + case 'ClientInitialisation': + this._sock.sQpush8(this._shared ? 1 : 0); // ClientInitialisation + this._sock.flush(); + this._rfbInitState = 'ServerInitialisation'; + return true; + + case 'ServerInitialisation': + return this._negotiateServerInit(); + + default: + return this._fail("Unknown init state (state: " + + this._rfbInitState + ")"); + } + } + + // Resume authentication handshake after it was paused for some + // reason, e.g. waiting for a password from the user + _resumeAuthentication() { + // We use setTimeout() so it's run in its own context, just like + // it originally did via the WebSocket's event handler + setTimeout(this._initMsg.bind(this), 0); + } + + _handleSetColourMapMsg() { + Log.Debug("SetColorMapEntries"); + + return this._fail("Unexpected SetColorMapEntries message"); + } + + _handleServerCutText() { + Log.Debug("ServerCutText"); + + if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; } + + this._sock.rQskipBytes(3); // Padding + + let length = this._sock.rQshift32(); + length = toSigned32bit(length); + + if (this._sock.rQwait("ServerCutText content", Math.abs(length), 8)) { return false; } + + if (length >= 0) { + //Standard msg + const text = this._sock.rQshiftStr(length); + if (this._viewOnly) { + return true; + } + + this.dispatchEvent(new CustomEvent( + "clipboard", + { detail: { text: text } })); + + } else { + //Extended msg. + length = Math.abs(length); + const flags = this._sock.rQshift32(); + let formats = flags & 0x0000FFFF; + let actions = flags & 0xFF000000; + + let isCaps = (!!(actions & extendedClipboardActionCaps)); + if (isCaps) { + this._clipboardServerCapabilitiesFormats = {}; + this._clipboardServerCapabilitiesActions = {}; + + // Update our server capabilities for Formats + for (let i = 0; i <= 15; i++) { + let index = 1 << i; + + // Check if format flag is set. + if ((formats & index)) { + this._clipboardServerCapabilitiesFormats[index] = true; + // We don't send unsolicited clipboard, so we + // ignore the size + this._sock.rQshift32(); + } + } + + // Update our server capabilities for Actions + for (let i = 24; i <= 31; i++) { + let index = 1 << i; + this._clipboardServerCapabilitiesActions[index] = !!(actions & index); + } + + /* Caps handling done, send caps with the clients + capabilities set as a response */ + let clientActions = [ + extendedClipboardActionCaps, + extendedClipboardActionRequest, + extendedClipboardActionPeek, + extendedClipboardActionNotify, + extendedClipboardActionProvide + ]; + RFB.messages.extendedClipboardCaps(this._sock, clientActions, {extendedClipboardFormatText: 0}); + + } else if (actions === extendedClipboardActionRequest) { + if (this._viewOnly) { + return true; + } + + // Check if server has told us it can handle Provide and there is clipboard data to send. + if (this._clipboardText != null && + this._clipboardServerCapabilitiesActions[extendedClipboardActionProvide]) { + + if (formats & extendedClipboardFormatText) { + RFB.messages.extendedClipboardProvide(this._sock, [extendedClipboardFormatText], [this._clipboardText]); + } + } + + } else if (actions === extendedClipboardActionPeek) { + if (this._viewOnly) { + return true; + } + + if (this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) { + + if (this._clipboardText != null) { + RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]); + } else { + RFB.messages.extendedClipboardNotify(this._sock, []); + } + } + + } else if (actions === extendedClipboardActionNotify) { + if (this._viewOnly) { + return true; + } + + if (this._clipboardServerCapabilitiesActions[extendedClipboardActionRequest]) { + + if (formats & extendedClipboardFormatText) { + RFB.messages.extendedClipboardRequest(this._sock, [extendedClipboardFormatText]); + } + } + + } else if (actions === extendedClipboardActionProvide) { + if (this._viewOnly) { + return true; + } + + if (!(formats & extendedClipboardFormatText)) { + return true; + } + // Ignore what we had in our clipboard client side. + this._clipboardText = null; + + // FIXME: Should probably verify that this data was actually requested + let zlibStream = this._sock.rQshiftBytes(length - 4); + let streamInflator = new Inflator(); + let textData = null; + + streamInflator.setInput(zlibStream); + for (let i = 0; i <= 15; i++) { + let format = 1 << i; + + if (formats & format) { + + let size = 0x00; + let sizeArray = streamInflator.inflate(4); + + size |= (sizeArray[0] << 24); + size |= (sizeArray[1] << 16); + size |= (sizeArray[2] << 8); + size |= (sizeArray[3]); + let chunk = streamInflator.inflate(size); + + if (format === extendedClipboardFormatText) { + textData = chunk; + } + } + } + streamInflator.setInput(null); + + if (textData !== null) { + let tmpText = ""; + for (let i = 0; i < textData.length; i++) { + tmpText += String.fromCharCode(textData[i]); + } + textData = tmpText; + + textData = decodeUTF8(textData); + if ((textData.length > 0) && "\0" === textData.charAt(textData.length - 1)) { + textData = textData.slice(0, -1); + } + + textData = textData.replaceAll("\r\n", "\n"); + + this.dispatchEvent(new CustomEvent( + "clipboard", + { detail: { text: textData } })); + } + } else { + return this._fail("Unexpected action in extended clipboard message: " + actions); + } + } + return true; + } + + _handleServerFenceMsg() { + if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; } + this._sock.rQskipBytes(3); // Padding + let flags = this._sock.rQshift32(); + let length = this._sock.rQshift8(); + + if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; } + + if (length > 64) { + Log.Warn("Bad payload length (" + length + ") in fence response"); + length = 64; + } + + const payload = this._sock.rQshiftStr(length); + + this._supportsFence = true; + + /* + * Fence flags + * + * (1<<0) - BlockBefore + * (1<<1) - BlockAfter + * (1<<2) - SyncNext + * (1<<31) - Request + */ + + if (!(flags & (1<<31))) { + return this._fail("Unexpected fence response"); + } + + // Filter out unsupported flags + // FIXME: support syncNext + flags &= (1<<0) | (1<<1); + + // BlockBefore and BlockAfter are automatically handled by + // the fact that we process each incoming message + // synchronuosly. + RFB.messages.clientFence(this._sock, flags, payload); + + return true; + } + + _handleXvpMsg() { + if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; } + this._sock.rQskipBytes(1); // Padding + const xvpVer = this._sock.rQshift8(); + const xvpMsg = this._sock.rQshift8(); + + switch (xvpMsg) { + case 0: // XVP_FAIL + Log.Error("XVP operation failed"); + break; + case 1: // XVP_INIT + this._rfbXvpVer = xvpVer; + Log.Info("XVP extensions enabled (version " + this._rfbXvpVer + ")"); + this._setCapability("power", true); + break; + default: + this._fail("Illegal server XVP message (msg: " + xvpMsg + ")"); + break; + } + + return true; + } + + _normalMsg() { + let msgType; + if (this._FBU.rects > 0) { + msgType = 0; + } else { + msgType = this._sock.rQshift8(); + } + + let first, ret; + switch (msgType) { + case 0: // FramebufferUpdate + ret = this._framebufferUpdate(); + if (ret && !this._enabledContinuousUpdates) { + RFB.messages.fbUpdateRequest(this._sock, true, 0, 0, + this._fbWidth, this._fbHeight); + } + return ret; + + case 1: // SetColorMapEntries + return this._handleSetColourMapMsg(); + + case 2: // Bell + Log.Debug("Bell"); + this.dispatchEvent(new CustomEvent( + "bell", + { detail: {} })); + return true; + + case 3: // ServerCutText + return this._handleServerCutText(); + + case 150: // EndOfContinuousUpdates + first = !this._supportsContinuousUpdates; + this._supportsContinuousUpdates = true; + this._enabledContinuousUpdates = false; + if (first) { + this._enabledContinuousUpdates = true; + this._updateContinuousUpdates(); + Log.Info("Enabling continuous updates."); + } else { + // FIXME: We need to send a framebufferupdaterequest here + // if we add support for turning off continuous updates + } + return true; + + case 248: // ServerFence + return this._handleServerFenceMsg(); + + case 250: // XVP + return this._handleXvpMsg(); + + default: + this._fail("Unexpected server message (type " + msgType + ")"); + Log.Debug("sock.rQpeekBytes(30): " + this._sock.rQpeekBytes(30)); + return true; + } + } + + _framebufferUpdate() { + if (this._FBU.rects === 0) { + if (this._sock.rQwait("FBU header", 3, 1)) { return false; } + this._sock.rQskipBytes(1); // Padding + this._FBU.rects = this._sock.rQshift16(); + + // Make sure the previous frame is fully rendered first + // to avoid building up an excessive queue + if (this._display.pending()) { + this._flushing = true; + this._display.flush() + .then(() => { + this._flushing = false; + // Resume processing + if (!this._sock.rQwait("message", 1)) { + this._handleMessage(); + } + }); + return false; + } + } + + while (this._FBU.rects > 0) { + if (this._FBU.encoding === null) { + if (this._sock.rQwait("rect header", 12)) { return false; } + /* New FramebufferUpdate */ + + this._FBU.x = this._sock.rQshift16(); + this._FBU.y = this._sock.rQshift16(); + this._FBU.width = this._sock.rQshift16(); + this._FBU.height = this._sock.rQshift16(); + this._FBU.encoding = this._sock.rQshift32(); + /* Encodings are signed */ + this._FBU.encoding >>= 0; + } + + if (!this._handleRect()) { + return false; + } + + this._FBU.rects--; + this._FBU.encoding = null; + } + + this._display.flip(); + + return true; // We finished this FBU + } + + _handleRect() { + switch (this._FBU.encoding) { + case encodings.pseudoEncodingLastRect: + this._FBU.rects = 1; // Will be decreased when we return + return true; + + case encodings.pseudoEncodingVMwareCursor: + return this._handleVMwareCursor(); + + case encodings.pseudoEncodingCursor: + return this._handleCursor(); + + case encodings.pseudoEncodingQEMUExtendedKeyEvent: + this._qemuExtKeyEventSupported = true; + return true; + + case encodings.pseudoEncodingDesktopName: + return this._handleDesktopName(); + + case encodings.pseudoEncodingDesktopSize: + this._resize(this._FBU.width, this._FBU.height); + return true; + + case encodings.pseudoEncodingExtendedDesktopSize: + return this._handleExtendedDesktopSize(); + + case encodings.pseudoEncodingExtendedMouseButtons: + this._extendedPointerEventSupported = true; + return true; + + case encodings.pseudoEncodingQEMULedEvent: + return this._handleLedEvent(); + + default: + return this._handleDataRect(); + } + } + + _handleVMwareCursor() { + const hotx = this._FBU.x; // hotspot-x + const hoty = this._FBU.y; // hotspot-y + const w = this._FBU.width; + const h = this._FBU.height; + if (this._sock.rQwait("VMware cursor encoding", 1)) { + return false; + } + + const cursorType = this._sock.rQshift8(); + + this._sock.rQshift8(); //Padding + + let rgba; + const bytesPerPixel = 4; + + //Classic cursor + if (cursorType == 0) { + //Used to filter away unimportant bits. + //OR is used for correct conversion in js. + const PIXEL_MASK = 0xffffff00 | 0; + rgba = new Array(w * h * bytesPerPixel); + + if (this._sock.rQwait("VMware cursor classic encoding", + (w * h * bytesPerPixel) * 2, 2)) { + return false; + } + + let andMask = new Array(w * h); + for (let pixel = 0; pixel < (w * h); pixel++) { + andMask[pixel] = this._sock.rQshift32(); + } + + let xorMask = new Array(w * h); + for (let pixel = 0; pixel < (w * h); pixel++) { + xorMask[pixel] = this._sock.rQshift32(); + } + + for (let pixel = 0; pixel < (w * h); pixel++) { + if (andMask[pixel] == 0) { + //Fully opaque pixel + let bgr = xorMask[pixel]; + let r = bgr >> 8 & 0xff; + let g = bgr >> 16 & 0xff; + let b = bgr >> 24 & 0xff; + + rgba[(pixel * bytesPerPixel) ] = r; //r + rgba[(pixel * bytesPerPixel) + 1 ] = g; //g + rgba[(pixel * bytesPerPixel) + 2 ] = b; //b + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; //a + + } else if ((andMask[pixel] & PIXEL_MASK) == + PIXEL_MASK) { + //Only screen value matters, no mouse colouring + if (xorMask[pixel] == 0) { + //Transparent pixel + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0x00; + + } else if ((xorMask[pixel] & PIXEL_MASK) == + PIXEL_MASK) { + //Inverted pixel, not supported in browsers. + //Fully opaque instead. + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + + } else { + //Unhandled xorMask + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + } + + } else { + //Unhandled andMask + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + } + } + + //Alpha cursor. + } else if (cursorType == 1) { + if (this._sock.rQwait("VMware cursor alpha encoding", + (w * h * 4), 2)) { + return false; + } + + rgba = new Array(w * h * bytesPerPixel); + + for (let pixel = 0; pixel < (w * h); pixel++) { + let data = this._sock.rQshift32(); + + rgba[(pixel * 4) ] = data >> 24 & 0xff; //r + rgba[(pixel * 4) + 1 ] = data >> 16 & 0xff; //g + rgba[(pixel * 4) + 2 ] = data >> 8 & 0xff; //b + rgba[(pixel * 4) + 3 ] = data & 0xff; //a + } + + } else { + Log.Warn("The given cursor type is not supported: " + + cursorType + " given."); + return false; + } + + this._updateCursor(rgba, hotx, hoty, w, h); + + return true; + } + + _handleCursor() { + const hotx = this._FBU.x; // hotspot-x + const hoty = this._FBU.y; // hotspot-y + const w = this._FBU.width; + const h = this._FBU.height; + + const pixelslength = w * h * 4; + const masklength = Math.ceil(w / 8) * h; + + let bytes = pixelslength + masklength; + if (this._sock.rQwait("cursor encoding", bytes)) { + return false; + } + + // Decode from BGRX pixels + bit mask to RGBA + const pixels = this._sock.rQshiftBytes(pixelslength); + const mask = this._sock.rQshiftBytes(masklength); + let rgba = new Uint8Array(w * h * 4); + + let pixIdx = 0; + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + let maskIdx = y * Math.ceil(w / 8) + Math.floor(x / 8); + let alpha = (mask[maskIdx] << (x % 8)) & 0x80 ? 255 : 0; + rgba[pixIdx ] = pixels[pixIdx + 2]; + rgba[pixIdx + 1] = pixels[pixIdx + 1]; + rgba[pixIdx + 2] = pixels[pixIdx]; + rgba[pixIdx + 3] = alpha; + pixIdx += 4; + } + } + + this._updateCursor(rgba, hotx, hoty, w, h); + + return true; + } + + _handleDesktopName() { + if (this._sock.rQwait("DesktopName", 4)) { + return false; + } + + let length = this._sock.rQshift32(); + + if (this._sock.rQwait("DesktopName", length, 4)) { + return false; + } + + let name = this._sock.rQshiftStr(length); + name = decodeUTF8(name, true); + + this._setDesktopName(name); + + return true; + } + + _handleLedEvent() { + if (this._sock.rQwait("LED status", 1)) { + return false; + } + + let data = this._sock.rQshift8(); + // ScrollLock state can be retrieved with data & 1. This is currently not needed. + let numLock = data & 2 ? true : false; + let capsLock = data & 4 ? true : false; + this._remoteCapsLock = capsLock; + this._remoteNumLock = numLock; + + return true; + } + + _handleExtendedDesktopSize() { + if (this._sock.rQwait("ExtendedDesktopSize", 4)) { + return false; + } + + const numberOfScreens = this._sock.rQpeek8(); + + let bytes = 4 + (numberOfScreens * 16); + if (this._sock.rQwait("ExtendedDesktopSize", bytes)) { + return false; + } + + const firstUpdate = !this._supportsSetDesktopSize; + this._supportsSetDesktopSize = true; + + this._sock.rQskipBytes(1); // number-of-screens + this._sock.rQskipBytes(3); // padding + + for (let i = 0; i < numberOfScreens; i += 1) { + // Save the id and flags of the first screen + if (i === 0) { + this._screenID = this._sock.rQshift32(); // id + this._sock.rQskipBytes(2); // x-position + this._sock.rQskipBytes(2); // y-position + this._sock.rQskipBytes(2); // width + this._sock.rQskipBytes(2); // height + this._screenFlags = this._sock.rQshift32(); // flags + } else { + this._sock.rQskipBytes(16); + } + } + + /* + * The x-position indicates the reason for the change: + * + * 0 - server resized on its own + * 1 - this client requested the resize + * 2 - another client requested the resize + */ + + if (this._FBU.x === 1) { + this._pendingRemoteResize = false; + } + + // We need to handle errors when we requested the resize. + if (this._FBU.x === 1 && this._FBU.y !== 0) { + let msg = ""; + // The y-position indicates the status code from the server + switch (this._FBU.y) { + case 1: + msg = "Resize is administratively prohibited"; + break; + case 2: + msg = "Out of resources"; + break; + case 3: + msg = "Invalid screen layout"; + break; + default: + msg = "Unknown reason"; + break; + } + Log.Warn("Server did not accept the resize request: " + + msg); + } else { + this._resize(this._FBU.width, this._FBU.height); + } + + // Normally we only apply the current resize mode after a + // window resize event. However there is no such trigger on the + // initial connect. And we don't know if the server supports + // resizing until we've gotten here. + if (firstUpdate) { + this._requestRemoteResize(); + } + + if (this._FBU.x === 1 && this._FBU.y === 0) { + // We might have resized again whilst waiting for the + // previous request, so check if we are in sync + this._requestRemoteResize(); + } + + return true; + } + + _handleDataRect() { + let decoder = this._decoders[this._FBU.encoding]; + if (!decoder) { + this._fail("Unsupported encoding (encoding: " + + this._FBU.encoding + ")"); + return false; + } + + try { + return decoder.decodeRect(this._FBU.x, this._FBU.y, + this._FBU.width, this._FBU.height, + this._sock, this._display, + this._fbDepth); + } catch (err) { + this._fail("Error decoding rect: " + err); + return false; + } + } + + _updateContinuousUpdates() { + if (!this._enabledContinuousUpdates) { return; } + + RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0, + this._fbWidth, this._fbHeight); + } + + // Handle resize-messages from the server + _resize(width, height) { + this._fbWidth = width; + this._fbHeight = height; + + this._display.resize(this._fbWidth, this._fbHeight); + + // Adjust the visible viewport based on the new dimensions + this._updateClip(); + this._updateScale(); + + this._updateContinuousUpdates(); + + // Keep this size until browser client size changes + this._saveExpectedClientSize(); + } + + _xvpOp(ver, op) { + if (this._rfbXvpVer < ver) { return; } + Log.Info("Sending XVP operation " + op + " (version " + ver + ")"); + RFB.messages.xvpOp(this._sock, ver, op); + } + + _updateCursor(rgba, hotx, hoty, w, h) { + this._cursorImage = { + rgbaPixels: rgba, + hotx: hotx, hoty: hoty, w: w, h: h, + }; + this._refreshCursor(); + } + + _shouldShowDotCursor() { + // Called when this._cursorImage is updated + if (!this._showDotCursor) { + // User does not want to see the dot, so... + return false; + } + + // The dot should not be shown if the cursor is already visible, + // i.e. contains at least one not-fully-transparent pixel. + // So iterate through all alpha bytes in rgba and stop at the + // first non-zero. + for (let i = 3; i < this._cursorImage.rgbaPixels.length; i += 4) { + if (this._cursorImage.rgbaPixels[i]) { + return false; + } + } + + // At this point, we know that the cursor is fully transparent, and + // the user wants to see the dot instead of this. + return true; + } + + _refreshCursor() { + if (this._rfbConnectionState !== "connecting" && + this._rfbConnectionState !== "connected") { + return; + } + const image = this._shouldShowDotCursor() ? RFB.cursors.dot : this._cursorImage; + this._cursor.change(image.rgbaPixels, + image.hotx, image.hoty, + image.w, image.h + ); + } + + static genDES(password, challenge) { + const passwordChars = password.split('').map(c => c.charCodeAt(0)); + const key = legacyCrypto.importKey( + "raw", passwordChars, { name: "DES-ECB" }, false, ["encrypt"]); + return legacyCrypto.encrypt({ name: "DES-ECB" }, key, challenge); + } +} + +// Class Methods +RFB.messages = { + keyEvent(sock, keysym, down) { + sock.sQpush8(4); // msg-type + sock.sQpush8(down); + + sock.sQpush16(0); + + sock.sQpush32(keysym); + + sock.flush(); + }, + + QEMUExtendedKeyEvent(sock, keysym, down, keycode) { + function getRFBkeycode(xtScanCode) { + const upperByte = (keycode >> 8); + const lowerByte = (keycode & 0x00ff); + if (upperByte === 0xe0 && lowerByte < 0x7f) { + return lowerByte | 0x80; + } + return xtScanCode; + } + + sock.sQpush8(255); // msg-type + sock.sQpush8(0); // sub msg-type + + sock.sQpush16(down); + + sock.sQpush32(keysym); + + const RFBkeycode = getRFBkeycode(keycode); + + sock.sQpush32(RFBkeycode); + + sock.flush(); + }, + + pointerEvent(sock, x, y, mask) { + sock.sQpush8(5); // msg-type + + // Marker bit must be set to 0, otherwise the server might + // confuse the marker bit with the highest bit in a normal + // PointerEvent message. + mask = mask & 0x7f; + sock.sQpush8(mask); + + sock.sQpush16(x); + sock.sQpush16(y); + + sock.flush(); + }, + + extendedPointerEvent(sock, x, y, mask) { + sock.sQpush8(5); // msg-type + + let higherBits = (mask >> 7) & 0xff; + + // Bits 2-7 are reserved + if (higherBits & 0xfc) { + throw new Error("Invalid mouse button mask: " + mask); + } + + let lowerBits = mask & 0x7f; + lowerBits |= 0x80; // Set marker bit to 1 + + sock.sQpush8(lowerBits); + sock.sQpush16(x); + sock.sQpush16(y); + sock.sQpush8(higherBits); + + sock.flush(); + }, + + // Used to build Notify and Request data. + _buildExtendedClipboardFlags(actions, formats) { + let data = new Uint8Array(4); + let formatFlag = 0x00000000; + let actionFlag = 0x00000000; + + for (let i = 0; i < actions.length; i++) { + actionFlag |= actions[i]; + } + + for (let i = 0; i < formats.length; i++) { + formatFlag |= formats[i]; + } + + data[0] = actionFlag >> 24; // Actions + data[1] = 0x00; // Reserved + data[2] = 0x00; // Reserved + data[3] = formatFlag; // Formats + + return data; + }, + + extendedClipboardProvide(sock, formats, inData) { + // Deflate incomming data and their sizes + let deflator = new Deflator(); + let dataToDeflate = []; + + for (let i = 0; i < formats.length; i++) { + // We only support the format Text at this time + if (formats[i] != extendedClipboardFormatText) { + throw new Error("Unsupported extended clipboard format for Provide message."); + } + + // Change lone \r or \n into \r\n as defined in rfbproto + inData[i] = inData[i].replace(/\r\n|\r|\n/gm, "\r\n"); + + // Check if it already has \0 + let text = encodeUTF8(inData[i] + "\0"); + + dataToDeflate.push( (text.length >> 24) & 0xFF, + (text.length >> 16) & 0xFF, + (text.length >> 8) & 0xFF, + (text.length & 0xFF)); + + for (let j = 0; j < text.length; j++) { + dataToDeflate.push(text.charCodeAt(j)); + } + } + + let deflatedData = deflator.deflate(new Uint8Array(dataToDeflate)); + + // Build data to send + let data = new Uint8Array(4 + deflatedData.length); + data.set(RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionProvide], + formats)); + data.set(deflatedData, 4); + + RFB.messages.clientCutText(sock, data, true); + }, + + extendedClipboardNotify(sock, formats) { + let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionNotify], + formats); + RFB.messages.clientCutText(sock, flags, true); + }, + + extendedClipboardRequest(sock, formats) { + let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionRequest], + formats); + RFB.messages.clientCutText(sock, flags, true); + }, + + extendedClipboardCaps(sock, actions, formats) { + let formatKeys = Object.keys(formats); + let data = new Uint8Array(4 + (4 * formatKeys.length)); + + formatKeys.map(x => parseInt(x)); + formatKeys.sort((a, b) => a - b); + + data.set(RFB.messages._buildExtendedClipboardFlags(actions, [])); + + let loopOffset = 4; + for (let i = 0; i < formatKeys.length; i++) { + data[loopOffset] = formats[formatKeys[i]] >> 24; + data[loopOffset + 1] = formats[formatKeys[i]] >> 16; + data[loopOffset + 2] = formats[formatKeys[i]] >> 8; + data[loopOffset + 3] = formats[formatKeys[i]] >> 0; + + loopOffset += 4; + data[3] |= (1 << formatKeys[i]); // Update our format flags + } + + RFB.messages.clientCutText(sock, data, true); + }, + + clientCutText(sock, data, extended = false) { + sock.sQpush8(6); // msg-type + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + let length; + if (extended) { + length = toUnsigned32bit(-data.length); + } else { + length = data.length; + } + + sock.sQpush32(length); + sock.sQpushBytes(data); + sock.flush(); + }, + + setDesktopSize(sock, width, height, id, flags) { + sock.sQpush8(251); // msg-type + + sock.sQpush8(0); // padding + + sock.sQpush16(width); + sock.sQpush16(height); + + sock.sQpush8(1); // number-of-screens + + sock.sQpush8(0); // padding + + // screen array + sock.sQpush32(id); + sock.sQpush16(0); // x-position + sock.sQpush16(0); // y-position + sock.sQpush16(width); + sock.sQpush16(height); + sock.sQpush32(flags); + + sock.flush(); + }, + + clientFence(sock, flags, payload) { + sock.sQpush8(248); // msg-type + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + sock.sQpush32(flags); + + sock.sQpush8(payload.length); + sock.sQpushString(payload); + + sock.flush(); + }, + + enableContinuousUpdates(sock, enable, x, y, width, height) { + sock.sQpush8(150); // msg-type + + sock.sQpush8(enable); + + sock.sQpush16(x); + sock.sQpush16(y); + sock.sQpush16(width); + sock.sQpush16(height); + + sock.flush(); + }, + + pixelFormat(sock, depth, trueColor) { + let bpp; + + if (depth > 16) { + bpp = 32; + } else if (depth > 8) { + bpp = 16; + } else { + bpp = 8; + } + + const bits = Math.floor(depth/3); + + sock.sQpush8(0); // msg-type + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + sock.sQpush8(bpp); + sock.sQpush8(depth); + sock.sQpush8(0); // little-endian + sock.sQpush8(trueColor ? 1 : 0); + + sock.sQpush16((1 << bits) - 1); // red-max + sock.sQpush16((1 << bits) - 1); // green-max + sock.sQpush16((1 << bits) - 1); // blue-max + + sock.sQpush8(bits * 0); // red-shift + sock.sQpush8(bits * 1); // green-shift + sock.sQpush8(bits * 2); // blue-shift + + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + sock.sQpush8(0); // padding + + sock.flush(); + }, + + clientEncodings(sock, encodings) { + sock.sQpush8(2); // msg-type + + sock.sQpush8(0); // padding + + sock.sQpush16(encodings.length); + for (let i = 0; i < encodings.length; i++) { + sock.sQpush32(encodings[i]); + } + + sock.flush(); + }, + + fbUpdateRequest(sock, incremental, x, y, w, h) { + if (typeof(x) === "undefined") { x = 0; } + if (typeof(y) === "undefined") { y = 0; } + + sock.sQpush8(3); // msg-type + + sock.sQpush8(incremental ? 1 : 0); + + sock.sQpush16(x); + sock.sQpush16(y); + sock.sQpush16(w); + sock.sQpush16(h); + + sock.flush(); + }, + + xvpOp(sock, ver, op) { + sock.sQpush8(250); // msg-type + + sock.sQpush8(0); // padding + + sock.sQpush8(ver); + sock.sQpush8(op); + + sock.flush(); + } +}; + +RFB.cursors = { + none: { + rgbaPixels: new Uint8Array(), + w: 0, h: 0, + hotx: 0, hoty: 0, + }, + + dot: { + /* eslint-disable indent */ + rgbaPixels: new Uint8Array([ + 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, + 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 255, + 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, + ]), + /* eslint-enable indent */ + w: 3, h: 3, + hotx: 1, hoty: 1, + } +}; diff --git a/web/public/cloud/vendor/novnc/core/util/browser.js b/web/public/cloud/vendor/novnc/core/util/browser.js new file mode 100644 index 00000000..63596d21 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/browser.js @@ -0,0 +1,233 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + * Browser feature support detection + */ + +import * as Log from './logging.js'; +import Base64 from '../base64.js'; + +// Touch detection +export let isTouchDevice = ('ontouchstart' in document.documentElement) || + // required for Chrome debugger + (document.ontouchstart !== undefined) || + // required for MS Surface + (navigator.maxTouchPoints > 0) || + (navigator.msMaxTouchPoints > 0); +window.addEventListener('touchstart', function onFirstTouch() { + isTouchDevice = true; + window.removeEventListener('touchstart', onFirstTouch, false); +}, false); + + +// The goal is to find a certain physical width, the devicePixelRatio +// brings us a bit closer but is not optimal. +export let dragThreshold = 10 * (window.devicePixelRatio || 1); + +let _supportsCursorURIs = false; + +try { + const target = document.createElement('canvas'); + target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default'; + + if (target.style.cursor.indexOf("url") === 0) { + Log.Info("Data URI scheme cursor supported"); + _supportsCursorURIs = true; + } else { + Log.Warn("Data URI scheme cursor not supported"); + } +} catch (exc) { + Log.Error("Data URI scheme cursor test exception: " + exc); +} + +export const supportsCursorURIs = _supportsCursorURIs; + +let _hasScrollbarGutter = true; +try { + // Create invisible container + const container = document.createElement('div'); + container.style.visibility = 'hidden'; + container.style.overflow = 'scroll'; // forcing scrollbars + document.body.appendChild(container); + + // Create a div and place it in the container + const child = document.createElement('div'); + container.appendChild(child); + + // Calculate the difference between the container's full width + // and the child's width - the difference is the scrollbars + const scrollbarWidth = (container.offsetWidth - child.offsetWidth); + + // Clean up + container.parentNode.removeChild(container); + + _hasScrollbarGutter = scrollbarWidth != 0; +} catch (exc) { + Log.Error("Scrollbar test exception: " + exc); +} +export const hasScrollbarGutter = _hasScrollbarGutter; + +export let supportsWebCodecsH264Decode = false; + +async function _checkWebCodecsH264DecodeSupport() { + if (!('VideoDecoder' in window)) { + return false; + } + + // We'll need to make do with some placeholders here + const config = { + codec: 'avc1.42401f', + codedWidth: 1920, + codedHeight: 1080, + optimizeForLatency: true, + }; + + let support = await VideoDecoder.isConfigSupported(config); + if (!support.supported) { + return false; + } + + // Firefox incorrectly reports supports for H.264 under some + // circumstances, so we need to actually test a real frame + // https://bugzilla.mozilla.org/show_bug.cgi?id=1932392 + + const data = new Uint8Array(Base64.decode( + 'AAAAAWdCwBTZnpuAgICgAAADACAAAAZB4oVNAAAAAWjJYyyAAAABBgX//4Hc' + + 'Rem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY0IHIzMTA4IDMxZTE5Zjkg' + + 'LSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDIz' + + 'IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9u' + + 'czogY2FiYWM9MCByZWY9NSBkZWJsb2NrPTE6MDowIGFuYWx5c2U9MHgxOjB4' + + 'MTExIG1lPWhleCBzdWJtZT04IHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4' + + 'ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0yIDh4' + + 'OGRjdD0wIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJv' + + 'bWFfcXBfb2Zmc2V0PS0yIHRocmVhZHM9MSBsb29rYWhlYWRfdGhyZWFkcz0x' + + 'IHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9' + + 'MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVz' + + 'PTAgd2VpZ2h0cD0wIGtleWludD1pbmZpbml0ZSBrZXlpbnRfbWluPTI1IHNj' + + 'ZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NTAgcmM9' + + 'YWJyIG1idHJlZT0xIGJpdHJhdGU9NDAwIHJhdGV0b2w9MS4wIHFjb21wPTAu' + + 'NjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFx' + + 'PTE6MS4wMACAAAABZYiEBrxmKAAPVccAAS044AA5DRJMnkycJk4TPw==')); + + let gotframe = false; + let error = null; + + let decoder = new VideoDecoder({ + output: (frame) => { gotframe = true; frame.close(); }, + error: (e) => { error = e; }, + }); + let chunk = new EncodedVideoChunk({ + timestamp: 0, + type: 'key', + data: data, + }); + + decoder.configure(config); + decoder.decode(chunk); + try { + await decoder.flush(); + } catch (e) { + // Firefox incorrectly throws an exception here + // https://bugzilla.mozilla.org/show_bug.cgi?id=1932566 + error = e; + } + + // Firefox fails to deliver the error on Windows, so we need to + // check if we got a frame instead + // https://bugzilla.mozilla.org/show_bug.cgi?id=1932579 + if (!gotframe) { + return false; + } + + if (error !== null) { + return false; + } + + return true; +} +supportsWebCodecsH264Decode = await _checkWebCodecsH264DecodeSupport(); + +/* + * The functions for detection of platforms and browsers below are exported + * but the use of these should be minimized as much as possible. + * + * It's better to use feature detection than platform detection. + */ + +/* OS */ + +export function isMac() { + return !!(/mac/i).exec(navigator.platform); +} + +export function isWindows() { + return !!(/win/i).exec(navigator.platform); +} + +export function isIOS() { + return (!!(/ipad/i).exec(navigator.platform) || + !!(/iphone/i).exec(navigator.platform) || + !!(/ipod/i).exec(navigator.platform)); +} + +export function isAndroid() { + /* Android sets navigator.platform to Linux :/ */ + return !!navigator.userAgent.match('Android '); +} + +export function isChromeOS() { + /* ChromeOS sets navigator.platform to Linux :/ */ + return !!navigator.userAgent.match(' CrOS '); +} + +/* Browser */ + +export function isSafari() { + return !!navigator.userAgent.match('Safari/...') && + !navigator.userAgent.match('Chrome/...') && + !navigator.userAgent.match('Chromium/...') && + !navigator.userAgent.match('Epiphany/...'); +} + +export function isFirefox() { + return !!navigator.userAgent.match('Firefox/...') && + !navigator.userAgent.match('Seamonkey/...'); +} + +export function isChrome() { + return !!navigator.userAgent.match('Chrome/...') && + !navigator.userAgent.match('Chromium/...') && + !navigator.userAgent.match('Edg/...') && + !navigator.userAgent.match('OPR/...'); +} + +export function isChromium() { + return !!navigator.userAgent.match('Chromium/...'); +} + +export function isOpera() { + return !!navigator.userAgent.match('OPR/...'); +} + +export function isEdge() { + return !!navigator.userAgent.match('Edg/...'); +} + +/* Engine */ + +export function isGecko() { + return !!navigator.userAgent.match('Gecko/...'); +} + +export function isWebKit() { + return !!navigator.userAgent.match('AppleWebKit/...') && + !navigator.userAgent.match('Chrome/...'); +} + +export function isBlink() { + return !!navigator.userAgent.match('Chrome/...'); +} diff --git a/web/public/cloud/vendor/novnc/core/util/cursor.js b/web/public/cloud/vendor/novnc/core/util/cursor.js new file mode 100644 index 00000000..6d689e7d --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/cursor.js @@ -0,0 +1,249 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 or any later version (see LICENSE.txt) + */ + +import { supportsCursorURIs, isTouchDevice } from './browser.js'; + +const useFallback = !supportsCursorURIs || isTouchDevice; + +export default class Cursor { + constructor() { + this._target = null; + + this._canvas = document.createElement('canvas'); + + if (useFallback) { + this._canvas.style.position = 'fixed'; + this._canvas.style.zIndex = '65535'; + this._canvas.style.pointerEvents = 'none'; + // Safari on iOS can select the cursor image + // https://bugs.webkit.org/show_bug.cgi?id=249223 + this._canvas.style.userSelect = 'none'; + this._canvas.style.WebkitUserSelect = 'none'; + // Can't use "display" because of Firefox bug #1445997 + this._canvas.style.visibility = 'hidden'; + } + + this._position = { x: 0, y: 0 }; + this._hotSpot = { x: 0, y: 0 }; + + this._eventHandlers = { + 'mouseover': this._handleMouseOver.bind(this), + 'mouseleave': this._handleMouseLeave.bind(this), + 'mousemove': this._handleMouseMove.bind(this), + 'mouseup': this._handleMouseUp.bind(this), + }; + } + + attach(target) { + if (this._target) { + this.detach(); + } + + this._target = target; + + if (useFallback) { + document.body.appendChild(this._canvas); + + const options = { capture: true, passive: true }; + this._target.addEventListener('mouseover', this._eventHandlers.mouseover, options); + this._target.addEventListener('mouseleave', this._eventHandlers.mouseleave, options); + this._target.addEventListener('mousemove', this._eventHandlers.mousemove, options); + this._target.addEventListener('mouseup', this._eventHandlers.mouseup, options); + } + + this.clear(); + } + + detach() { + if (!this._target) { + return; + } + + if (useFallback) { + const options = { capture: true, passive: true }; + this._target.removeEventListener('mouseover', this._eventHandlers.mouseover, options); + this._target.removeEventListener('mouseleave', this._eventHandlers.mouseleave, options); + this._target.removeEventListener('mousemove', this._eventHandlers.mousemove, options); + this._target.removeEventListener('mouseup', this._eventHandlers.mouseup, options); + + if (document.contains(this._canvas)) { + document.body.removeChild(this._canvas); + } + } + + this._target = null; + } + + change(rgba, hotx, hoty, w, h) { + if ((w === 0) || (h === 0)) { + this.clear(); + return; + } + + this._position.x = this._position.x + this._hotSpot.x - hotx; + this._position.y = this._position.y + this._hotSpot.y - hoty; + this._hotSpot.x = hotx; + this._hotSpot.y = hoty; + + let ctx = this._canvas.getContext('2d'); + + this._canvas.width = w; + this._canvas.height = h; + + let img = new ImageData(new Uint8ClampedArray(rgba), w, h); + ctx.clearRect(0, 0, w, h); + ctx.putImageData(img, 0, 0); + + if (useFallback) { + this._updatePosition(); + } else { + let url = this._canvas.toDataURL(); + this._target.style.cursor = 'url(' + url + ')' + hotx + ' ' + hoty + ', default'; + } + } + + clear() { + this._target.style.cursor = 'none'; + this._canvas.width = 0; + this._canvas.height = 0; + this._position.x = this._position.x + this._hotSpot.x; + this._position.y = this._position.y + this._hotSpot.y; + this._hotSpot.x = 0; + this._hotSpot.y = 0; + } + + // Mouse events might be emulated, this allows + // moving the cursor in such cases + move(clientX, clientY) { + if (!useFallback) { + return; + } + // clientX/clientY are relative the _visual viewport_, + // but our position is relative the _layout viewport_, + // so try to compensate when we can + if (window.visualViewport) { + this._position.x = clientX + window.visualViewport.offsetLeft; + this._position.y = clientY + window.visualViewport.offsetTop; + } else { + this._position.x = clientX; + this._position.y = clientY; + } + this._updatePosition(); + let target = document.elementFromPoint(clientX, clientY); + this._updateVisibility(target); + } + + _handleMouseOver(event) { + // This event could be because we're entering the target, or + // moving around amongst its sub elements. Let the move handler + // sort things out. + this._handleMouseMove(event); + } + + _handleMouseLeave(event) { + // Check if we should show the cursor on the element we are leaving to + this._updateVisibility(event.relatedTarget); + } + + _handleMouseMove(event) { + this._updateVisibility(event.target); + + this._position.x = event.clientX - this._hotSpot.x; + this._position.y = event.clientY - this._hotSpot.y; + + this._updatePosition(); + } + + _handleMouseUp(event) { + // We might get this event because of a drag operation that + // moved outside of the target. Check what's under the cursor + // now and adjust visibility based on that. + let target = document.elementFromPoint(event.clientX, event.clientY); + this._updateVisibility(target); + + // Captures end with a mouseup but we can't know the event order of + // mouseup vs releaseCapture. + // + // In the cases when releaseCapture comes first, the code above is + // enough. + // + // In the cases when the mouseup comes first, we need wait for the + // browser to flush all events and then check again if the cursor + // should be visible. + if (this._captureIsActive()) { + window.setTimeout(() => { + // We might have detached at this point + if (!this._target) { + return; + } + // Refresh the target from elementFromPoint since queued events + // might have altered the DOM + target = document.elementFromPoint(event.clientX, + event.clientY); + this._updateVisibility(target); + }, 0); + } + } + + _showCursor() { + if (this._canvas.style.visibility === 'hidden') { + this._canvas.style.visibility = ''; + } + } + + _hideCursor() { + if (this._canvas.style.visibility !== 'hidden') { + this._canvas.style.visibility = 'hidden'; + } + } + + // Should we currently display the cursor? + // (i.e. are we over the target, or a child of the target without a + // different cursor set) + _shouldShowCursor(target) { + if (!target) { + return false; + } + // Easy case + if (target === this._target) { + return true; + } + // Other part of the DOM? + if (!this._target.contains(target)) { + return false; + } + // Has the child its own cursor? + // FIXME: How can we tell that a sub element has an + // explicit "cursor: none;"? + if (window.getComputedStyle(target).cursor !== 'none') { + return false; + } + return true; + } + + _updateVisibility(target) { + // When the cursor target has capture we want to show the cursor. + // So, if a capture is active - look at the captured element instead. + if (this._captureIsActive()) { + target = document.captureElement; + } + if (this._shouldShowCursor(target)) { + this._showCursor(); + } else { + this._hideCursor(); + } + } + + _updatePosition() { + this._canvas.style.left = this._position.x + "px"; + this._canvas.style.top = this._position.y + "px"; + } + + _captureIsActive() { + return document.captureElement && + document.documentElement.contains(document.captureElement); + } +} diff --git a/web/public/cloud/vendor/novnc/core/util/element.js b/web/public/cloud/vendor/novnc/core/util/element.js new file mode 100644 index 00000000..17d82d58 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/element.js @@ -0,0 +1,32 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * HTML element utility functions + */ + +export function clientToElement(x, y, elem) { + const bounds = elem.getBoundingClientRect(); + let pos = { x: 0, y: 0 }; + // Clip to target bounds + if (x < bounds.left) { + pos.x = 0; + } else if (x >= bounds.right) { + pos.x = bounds.width - 1; + } else { + pos.x = x - bounds.left; + } + if (y < bounds.top) { + pos.y = 0; + } else if (y >= bounds.bottom) { + pos.y = bounds.height - 1; + } else { + pos.y = y - bounds.top; + } + return pos; +} diff --git a/web/public/cloud/vendor/novnc/core/util/events.js b/web/public/cloud/vendor/novnc/core/util/events.js new file mode 100644 index 00000000..26aa9790 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/events.js @@ -0,0 +1,138 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2018 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * Cross-browser event and position routines + */ + +export function getPointerEvent(e) { + return e.changedTouches ? e.changedTouches[0] : e.touches ? e.touches[0] : e; +} + +export function stopEvent(e) { + e.stopPropagation(); + e.preventDefault(); +} + +// Emulate Element.setCapture() when not supported +let _captureRecursion = false; +let _elementForUnflushedEvents = null; +document.captureElement = null; +function _captureProxy(e) { + // Recursion protection as we'll see our own event + if (_captureRecursion) return; + + // Clone the event as we cannot dispatch an already dispatched event + const newEv = new e.constructor(e.type, e); + + _captureRecursion = true; + if (document.captureElement) { + document.captureElement.dispatchEvent(newEv); + } else { + _elementForUnflushedEvents.dispatchEvent(newEv); + } + _captureRecursion = false; + + // Avoid double events + e.stopPropagation(); + + // Respect the wishes of the redirected event handlers + if (newEv.defaultPrevented) { + e.preventDefault(); + } + + // Implicitly release the capture on button release + if (e.type === "mouseup") { + releaseCapture(); + } +} + +// Follow cursor style of target element +function _capturedElemChanged() { + const proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + proxyElem.style.cursor = window.getComputedStyle(document.captureElement).cursor; +} + +const _captureObserver = new MutationObserver(_capturedElemChanged); + +export function setCapture(target) { + if (target.setCapture) { + + target.setCapture(); + document.captureElement = target; + } else { + // Release any existing capture in case this method is + // called multiple times without coordination + releaseCapture(); + + let proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + + if (proxyElem === null) { + proxyElem = document.createElement("div"); + proxyElem.id = "noVNC_mouse_capture_elem"; + proxyElem.style.position = "fixed"; + proxyElem.style.top = "0px"; + proxyElem.style.left = "0px"; + proxyElem.style.width = "100%"; + proxyElem.style.height = "100%"; + proxyElem.style.zIndex = 10000; + proxyElem.style.display = "none"; + document.body.appendChild(proxyElem); + + // This is to make sure callers don't get confused by having + // our blocking element as the target + proxyElem.addEventListener('contextmenu', _captureProxy); + + proxyElem.addEventListener('mousemove', _captureProxy); + proxyElem.addEventListener('mouseup', _captureProxy); + } + + document.captureElement = target; + + // Track cursor and get initial cursor + _captureObserver.observe(target, {attributes: true}); + _capturedElemChanged(); + + proxyElem.style.display = ""; + + // We listen to events on window in order to keep tracking if it + // happens to leave the viewport + window.addEventListener('mousemove', _captureProxy); + window.addEventListener('mouseup', _captureProxy); + } +} + +export function releaseCapture() { + if (document.releaseCapture) { + + document.releaseCapture(); + document.captureElement = null; + + } else { + if (!document.captureElement) { + return; + } + + // There might be events already queued. The event proxy needs + // access to the captured element for these queued events. + // E.g. contextmenu (right-click) in Microsoft Edge + // + // Before removing the capturedElem pointer we save it to a + // temporary variable that the unflushed events can use. + _elementForUnflushedEvents = document.captureElement; + document.captureElement = null; + + _captureObserver.disconnect(); + + const proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + proxyElem.style.display = "none"; + + window.removeEventListener('mousemove', _captureProxy); + window.removeEventListener('mouseup', _captureProxy); + } +} diff --git a/web/public/cloud/vendor/novnc/core/util/eventtarget.js b/web/public/cloud/vendor/novnc/core/util/eventtarget.js new file mode 100644 index 00000000..547bf5fa --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/eventtarget.js @@ -0,0 +1,35 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +export default class EventTargetMixin { + constructor() { + this._listeners = new Map(); + } + + addEventListener(type, callback) { + if (!this._listeners.has(type)) { + this._listeners.set(type, new Set()); + } + this._listeners.get(type).add(callback); + } + + removeEventListener(type, callback) { + if (this._listeners.has(type)) { + this._listeners.get(type).delete(callback); + } + } + + dispatchEvent(event) { + if (!this._listeners.has(event.type)) { + return true; + } + this._listeners.get(event.type) + .forEach(callback => callback.call(this, event)); + return !event.defaultPrevented; + } +} diff --git a/web/public/cloud/vendor/novnc/core/util/int.js b/web/public/cloud/vendor/novnc/core/util/int.js new file mode 100644 index 00000000..303ddc5f --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/int.js @@ -0,0 +1,15 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +export function toUnsigned32bit(toConvert) { + return toConvert >>> 0; +} + +export function toSigned32bit(toConvert) { + return toConvert | 0; +} diff --git a/web/public/cloud/vendor/novnc/core/util/logging.js b/web/public/cloud/vendor/novnc/core/util/logging.js new file mode 100644 index 00000000..0db08385 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/logging.js @@ -0,0 +1,56 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * Logging/debug routines + */ + +let _logLevel = 'warn'; + +let Debug = () => {}; +let Info = () => {}; +let Warn = () => {}; +let Error = () => {}; + +export function initLogging(level) { + if (typeof level === 'undefined') { + level = _logLevel; + } else { + _logLevel = level; + } + + Debug = Info = Warn = Error = () => {}; + + if (typeof window.console !== "undefined") { + /* eslint-disable no-console, no-fallthrough */ + switch (level) { + case 'debug': + Debug = console.debug.bind(window.console); + case 'info': + Info = console.info.bind(window.console); + case 'warn': + Warn = console.warn.bind(window.console); + case 'error': + Error = console.error.bind(window.console); + case 'none': + break; + default: + throw new window.Error("invalid logging type '" + level + "'"); + } + /* eslint-enable no-console, no-fallthrough */ + } +} + +export function getLogging() { + return _logLevel; +} + +export { Debug, Info, Warn, Error }; + +// Initialize logging level +initLogging(); diff --git a/web/public/cloud/vendor/novnc/core/util/strings.js b/web/public/cloud/vendor/novnc/core/util/strings.js new file mode 100644 index 00000000..432b0a9d --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/util/strings.js @@ -0,0 +1,28 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +// Decode from UTF-8 +export function decodeUTF8(utf8string, allowLatin1=false) { + try { + return decodeURIComponent(escape(utf8string)); + } catch (e) { + if (e instanceof URIError) { + if (allowLatin1) { + // If we allow Latin1 we can ignore any decoding fails + // and in these cases return the original string + return utf8string; + } + } + throw e; + } +} + +// Encode to UTF-8 +export function encodeUTF8(DOMString) { + return unescape(encodeURIComponent(DOMString)); +} diff --git a/web/public/cloud/vendor/novnc/core/websock.js b/web/public/cloud/vendor/novnc/core/websock.js new file mode 100644 index 00000000..ee8a4bc4 --- /dev/null +++ b/web/public/cloud/vendor/novnc/core/websock.js @@ -0,0 +1,369 @@ +/* + * Websock: high-performance buffering wrapper + * Copyright (C) 2019 The noVNC authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * Websock is similar to the standard WebSocket / RTCDataChannel object + * but with extra buffer handling. + * + * Websock has built-in receive queue buffering; the message event + * does not contain actual data but is simply a notification that + * there is new data available. Several rQ* methods are available to + * read binary data off of the receive queue. + */ + +import * as Log from './util/logging.js'; + +// this has performance issues in some versions Chromium, and +// doesn't gain a tremendous amount of performance increase in Firefox +// at the moment. It may be valuable to turn it on in the future. +const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB + +// Constants pulled from RTCDataChannelState enum +// https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/readyState#RTCDataChannelState_enum +const DataChannel = { + CONNECTING: "connecting", + OPEN: "open", + CLOSING: "closing", + CLOSED: "closed" +}; + +const ReadyStates = { + CONNECTING: [WebSocket.CONNECTING, DataChannel.CONNECTING], + OPEN: [WebSocket.OPEN, DataChannel.OPEN], + CLOSING: [WebSocket.CLOSING, DataChannel.CLOSING], + CLOSED: [WebSocket.CLOSED, DataChannel.CLOSED], +}; + +// Properties a raw channel must have, WebSocket and RTCDataChannel are two examples +const rawChannelProps = [ + "send", + "close", + "binaryType", + "onerror", + "onmessage", + "onopen", + "protocol", + "readyState", +]; + +export default class Websock { + constructor() { + this._websocket = null; // WebSocket or RTCDataChannel object + + this._rQi = 0; // Receive queue index + this._rQlen = 0; // Next write position in the receive queue + this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB) + // called in init: this._rQ = new Uint8Array(this._rQbufferSize); + this._rQ = null; // Receive queue + + this._sQbufferSize = 1024 * 10; // 10 KiB + // called in init: this._sQ = new Uint8Array(this._sQbufferSize); + this._sQlen = 0; + this._sQ = null; // Send queue + + this._eventHandlers = { + message: () => {}, + open: () => {}, + close: () => {}, + error: () => {} + }; + } + + // Getters and setters + + get readyState() { + let subState; + + if (this._websocket === null) { + return "unused"; + } + + subState = this._websocket.readyState; + + if (ReadyStates.CONNECTING.includes(subState)) { + return "connecting"; + } else if (ReadyStates.OPEN.includes(subState)) { + return "open"; + } else if (ReadyStates.CLOSING.includes(subState)) { + return "closing"; + } else if (ReadyStates.CLOSED.includes(subState)) { + return "closed"; + } + + return "unknown"; + } + + // Receive queue + rQpeek8() { + return this._rQ[this._rQi]; + } + + rQskipBytes(bytes) { + this._rQi += bytes; + } + + rQshift8() { + return this._rQshift(1); + } + + rQshift16() { + return this._rQshift(2); + } + + rQshift32() { + return this._rQshift(4); + } + + // TODO(directxman12): test performance with these vs a DataView + _rQshift(bytes) { + let res = 0; + for (let byte = bytes - 1; byte >= 0; byte--) { + res += this._rQ[this._rQi++] << (byte * 8); + } + return res >>> 0; + } + + rQlen() { + return this._rQlen - this._rQi; + } + + rQshiftStr(len) { + let str = ""; + // Handle large arrays in steps to avoid long strings on the stack + for (let i = 0; i < len; i += 4096) { + let part = this.rQshiftBytes(Math.min(4096, len - i), false); + str += String.fromCharCode.apply(null, part); + } + return str; + } + + rQshiftBytes(len, copy=true) { + this._rQi += len; + if (copy) { + return this._rQ.slice(this._rQi - len, this._rQi); + } else { + return this._rQ.subarray(this._rQi - len, this._rQi); + } + } + + rQshiftTo(target, len) { + // TODO: make this just use set with views when using a ArrayBuffer to store the rQ + target.set(new Uint8Array(this._rQ.buffer, this._rQi, len)); + this._rQi += len; + } + + rQpeekBytes(len, copy=true) { + if (copy) { + return this._rQ.slice(this._rQi, this._rQi + len); + } else { + return this._rQ.subarray(this._rQi, this._rQi + len); + } + } + + // Check to see if we must wait for 'num' bytes (default to FBU.bytes) + // to be available in the receive queue. Return true if we need to + // wait (and possibly print a debug message), otherwise false. + rQwait(msg, num, goback) { + if (this._rQlen - this._rQi < num) { + if (goback) { + if (this._rQi < goback) { + throw new Error("rQwait cannot backup " + goback + " bytes"); + } + this._rQi -= goback; + } + return true; // true means need more data + } + return false; + } + + // Send queue + + sQpush8(num) { + this._sQensureSpace(1); + this._sQ[this._sQlen++] = num; + } + + sQpush16(num) { + this._sQensureSpace(2); + this._sQ[this._sQlen++] = (num >> 8) & 0xff; + this._sQ[this._sQlen++] = (num >> 0) & 0xff; + } + + sQpush32(num) { + this._sQensureSpace(4); + this._sQ[this._sQlen++] = (num >> 24) & 0xff; + this._sQ[this._sQlen++] = (num >> 16) & 0xff; + this._sQ[this._sQlen++] = (num >> 8) & 0xff; + this._sQ[this._sQlen++] = (num >> 0) & 0xff; + } + + sQpushString(str) { + let bytes = str.split('').map(chr => chr.charCodeAt(0)); + this.sQpushBytes(new Uint8Array(bytes)); + } + + sQpushBytes(bytes) { + for (let offset = 0;offset < bytes.length;) { + this._sQensureSpace(1); + + let chunkSize = this._sQbufferSize - this._sQlen; + if (chunkSize > bytes.length - offset) { + chunkSize = bytes.length - offset; + } + + this._sQ.set(bytes.subarray(offset, offset + chunkSize), this._sQlen); + this._sQlen += chunkSize; + offset += chunkSize; + } + } + + flush() { + if (this._sQlen > 0 && this.readyState === 'open') { + this._websocket.send(new Uint8Array(this._sQ.buffer, 0, this._sQlen)); + this._sQlen = 0; + } + } + + _sQensureSpace(bytes) { + if (this._sQbufferSize - this._sQlen < bytes) { + this.flush(); + } + } + + // Event handlers + off(evt) { + this._eventHandlers[evt] = () => {}; + } + + on(evt, handler) { + this._eventHandlers[evt] = handler; + } + + _allocateBuffers() { + this._rQ = new Uint8Array(this._rQbufferSize); + this._sQ = new Uint8Array(this._sQbufferSize); + } + + init() { + this._allocateBuffers(); + this._rQi = 0; + this._websocket = null; + } + + open(uri, protocols) { + this.attach(new WebSocket(uri, protocols)); + } + + attach(rawChannel) { + this.init(); + + // Must get object and class methods to be compatible with the tests. + const channelProps = [...Object.keys(rawChannel), ...Object.getOwnPropertyNames(Object.getPrototypeOf(rawChannel))]; + for (let i = 0; i < rawChannelProps.length; i++) { + const prop = rawChannelProps[i]; + if (channelProps.indexOf(prop) < 0) { + throw new Error('Raw channel missing property: ' + prop); + } + } + + this._websocket = rawChannel; + this._websocket.binaryType = "arraybuffer"; + this._websocket.onmessage = this._recvMessage.bind(this); + + this._websocket.onopen = () => { + Log.Debug('>> WebSock.onopen'); + if (this._websocket.protocol) { + Log.Info("Server choose sub-protocol: " + this._websocket.protocol); + } + + this._eventHandlers.open(); + Log.Debug("<< WebSock.onopen"); + }; + + this._websocket.onclose = (e) => { + Log.Debug(">> WebSock.onclose"); + this._eventHandlers.close(e); + Log.Debug("<< WebSock.onclose"); + }; + + this._websocket.onerror = (e) => { + Log.Debug(">> WebSock.onerror: " + e); + this._eventHandlers.error(e); + Log.Debug("<< WebSock.onerror: " + e); + }; + } + + close() { + if (this._websocket) { + if (this.readyState === 'connecting' || + this.readyState === 'open') { + Log.Info("Closing WebSocket connection"); + this._websocket.close(); + } + + this._websocket.onmessage = () => {}; + } + } + + // private methods + + // We want to move all the unread data to the start of the queue, + // e.g. compacting. + // The function also expands the receive que if needed, and for + // performance reasons we combine these two actions to avoid + // unnecessary copying. + _expandCompactRQ(minFit) { + // if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place + // instead of resizing + const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8; + const resizeNeeded = this._rQbufferSize < requiredBufferSize; + + if (resizeNeeded) { + // Make sure we always *at least* double the buffer size, and have at least space for 8x + // the current amount of data + this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize); + } + + // we don't want to grow unboundedly + if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { + this._rQbufferSize = MAX_RQ_GROW_SIZE; + if (this._rQbufferSize - (this._rQlen - this._rQi) < minFit) { + throw new Error("Receive queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); + } + } + + if (resizeNeeded) { + const oldRQbuffer = this._rQ.buffer; + this._rQ = new Uint8Array(this._rQbufferSize); + this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi)); + } else { + this._rQ.copyWithin(0, this._rQi, this._rQlen); + } + + this._rQlen = this._rQlen - this._rQi; + this._rQi = 0; + } + + // push arraybuffer values onto the end of the receive que + _recvMessage(e) { + if (this._rQlen == this._rQi) { + // All data has now been processed, this means we + // can reset the receive queue. + this._rQlen = 0; + this._rQi = 0; + } + const u8 = new Uint8Array(e.data); + if (u8.length > this._rQbufferSize - this._rQlen) { + this._expandCompactRQ(u8.length); + } + this._rQ.set(u8, this._rQlen); + this._rQlen += u8.length; + + if (this._rQlen - this._rQi > 0) { + this._eventHandlers.message(); + } else { + Log.Debug("Ignoring empty message"); + } + } +} diff --git a/web/public/cloud/vendor/novnc/vendor/pako/LICENSE b/web/public/cloud/vendor/novnc/vendor/pako/LICENSE new file mode 100644 index 00000000..d082ae32 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2014-2016 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/web/public/cloud/vendor/novnc/vendor/pako/README.md b/web/public/cloud/vendor/novnc/vendor/pako/README.md new file mode 100644 index 00000000..755df643 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/README.md @@ -0,0 +1,6 @@ +This is an ES6-modules-compatible version of +https://github.com/nodeca/pako, based on pako version 1.0.3. + +It's more-or-less a direct translation of the original, with unused parts +removed, and the dynamic support for non-typed arrays removed (since ES6 +modules don't work well with dynamic exports). diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/utils/common.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/utils/common.js new file mode 100644 index 00000000..576fd59d --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/utils/common.js @@ -0,0 +1,45 @@ +// reduce buffer size, avoiding mem copy +export function shrinkBuf (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +export function arraySet (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } +} + +// Join array of chunks to single array. +export function flattenChunks (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; +} + +export var Buf8 = Uint8Array; +export var Buf16 = Uint16Array; +export var Buf32 = Int32Array; diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/adler32.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/adler32.js new file mode 100644 index 00000000..058a534a --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/adler32.js @@ -0,0 +1,27 @@ +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It doesn't worth to make additional optimizationa as in original. +// Small size is preferable. + +export default function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/constants.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/constants.js new file mode 100644 index 00000000..7d80502d --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/constants.js @@ -0,0 +1,47 @@ +export default { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/crc32.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/crc32.js new file mode 100644 index 00000000..611ffb29 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/crc32.js @@ -0,0 +1,36 @@ +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + + +// Use ordinary array, since untyped makes no boost here +export default function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/deflate.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/deflate.js new file mode 100644 index 00000000..c3a5ba49 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/deflate.js @@ -0,0 +1,1846 @@ +import * as utils from "../utils/common.js"; +import * as trees from "./trees.js"; +import adler32 from "./adler32.js"; +import crc32 from "./crc32.js"; +import msg from "./messages.js"; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +export const Z_NO_FLUSH = 0; +export const Z_PARTIAL_FLUSH = 1; +//export const Z_SYNC_FLUSH = 2; +export const Z_FULL_FLUSH = 3; +export const Z_FINISH = 4; +export const Z_BLOCK = 5; +//export const Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +export const Z_OK = 0; +export const Z_STREAM_END = 1; +//export const Z_NEED_DICT = 2; +//export const Z_ERRNO = -1; +export const Z_STREAM_ERROR = -2; +export const Z_DATA_ERROR = -3; +//export const Z_MEM_ERROR = -4; +export const Z_BUF_ERROR = -5; +//export const Z_VERSION_ERROR = -6; + + +/* compression levels */ +//export const Z_NO_COMPRESSION = 0; +//export const Z_BEST_SPEED = 1; +//export const Z_BEST_COMPRESSION = 9; +export const Z_DEFAULT_COMPRESSION = -1; + + +export const Z_FILTERED = 1; +export const Z_HUFFMAN_ONLY = 2; +export const Z_RLE = 3; +export const Z_FIXED = 4; +export const Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//export const Z_BINARY = 0; +//export const Z_TEXT = 1; +//export const Z_ASCII = 1; // = Z_TEXT +export const Z_UNKNOWN = 2; + + +/* The deflate compression method */ +export const Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + // Do nothing + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + // Do nothing + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +export { deflateInit, deflateInit2, deflateReset, deflateResetKeep, deflateSetHeader, deflate, deflateEnd, deflateSetDictionary }; +export var deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/gzheader.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/gzheader.js new file mode 100644 index 00000000..2ec586d3 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/gzheader.js @@ -0,0 +1,35 @@ +export default function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inffast.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inffast.js new file mode 100644 index 00000000..889dcc7a --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inffast.js @@ -0,0 +1,324 @@ +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +export default function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inflate.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inflate.js new file mode 100644 index 00000000..1d2063bc --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inflate.js @@ -0,0 +1,1527 @@ +import * as utils from "../utils/common.js"; +import adler32 from "./adler32.js"; +import crc32 from "./crc32.js"; +import inflate_fast from "./inffast.js"; +import inflate_table from "./inftrees.js"; + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//export const Z_NO_FLUSH = 0; +//export const Z_PARTIAL_FLUSH = 1; +//export const Z_SYNC_FLUSH = 2; +//export const Z_FULL_FLUSH = 3; +export const Z_FINISH = 4; +export const Z_BLOCK = 5; +export const Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +export const Z_OK = 0; +export const Z_STREAM_END = 1; +export const Z_NEED_DICT = 2; +//export const Z_ERRNO = -1; +export const Z_STREAM_ERROR = -2; +export const Z_DATA_ERROR = -3; +export const Z_MEM_ERROR = -4; +export const Z_BUF_ERROR = -5; +//export const Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +export const Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more conveniend processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' insdead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +export { inflateReset, inflateReset2, inflateResetKeep, inflateInit, inflateInit2, inflate, inflateEnd, inflateGetHeader, inflateSetDictionary }; +export var inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inftrees.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inftrees.js new file mode 100644 index 00000000..78b7c9eb --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/inftrees.js @@ -0,0 +1,322 @@ +import * as utils from "../utils/common.js"; + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +export default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/messages.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/messages.js new file mode 100644 index 00000000..f95cb704 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/messages.js @@ -0,0 +1,11 @@ +export default { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/trees.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/trees.js new file mode 100644 index 00000000..a69b8a59 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/trees.js @@ -0,0 +1,1195 @@ +import * as utils from "../utils/common.js"; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +export { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align }; diff --git a/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/zstream.js b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/zstream.js new file mode 100644 index 00000000..e7e674e7 --- /dev/null +++ b/web/public/cloud/vendor/novnc/vendor/pako/lib/zlib/zstream.js @@ -0,0 +1,24 @@ +export default function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} diff --git a/web/resources/views/venix/admin/cloud/instances.tpl b/web/resources/views/venix/admin/cloud/instances.tpl new file mode 100644 index 00000000..c829fe8c --- /dev/null +++ b/web/resources/views/venix/admin/cloud/instances.tpl @@ -0,0 +1,2 @@ +{assign var=admin_title value='虚拟机实例'}{assign var=admin_active value='cloud_instances'}{include file='admin/static_header.tpl'} +

虚拟机实例

跨宿主机查看已关联的实例和所属用户。客户的资源与操作权限由后台校验。

正在加载…

实例用户宿主机状态公网 IP配置
{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/cloud/orders.tpl b/web/resources/views/venix/admin/cloud/orders.tpl new file mode 100644 index 00000000..1c346579 --- /dev/null +++ b/web/resources/views/venix/admin/cloud/orders.tpl @@ -0,0 +1,2 @@ +{assign var=admin_title value='开通订单'}{assign var=admin_active value='cloud_orders'}{include file='admin/static_header.tpl'} +

余额开通订单

首版采用余额一次性购买,不包含自动到期续费。失败或不确定的开通任务需核查实际宿主机状态,不要重复创建或扣款。

正在加载…

订单用户套餐金额状态实例 / 任务时间 / 错误
{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/cloud/rescue.tpl b/web/resources/views/venix/admin/cloud/rescue.tpl new file mode 100644 index 00000000..f5395941 --- /dev/null +++ b/web/resources/views/venix/admin/cloud/rescue.tpl @@ -0,0 +1,4 @@ +{assign var=admin_title value='救援模版'}{assign var=admin_active value='cloud_rescue'}{include file='admin/static_header.tpl'} + +

救援模版

只支持可启动 ISO,上传至所选宿主机的独立救援目录;不会混入普通安装 ISO 列表。救援系统自身决定登录方式。

正在加载…

上传救援 ISO

上传大小还受 PHP、Web 服务器及反代限制;完成前请勿关闭页面。

救援 ISO 列表
+{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/cloud/templates.tpl b/web/resources/views/venix/admin/cloud/templates.tpl new file mode 100644 index 00000000..d6d3c411 --- /dev/null +++ b/web/resources/views/venix/admin/cloud/templates.tpl @@ -0,0 +1,5 @@ +{assign var=admin_title value='云镜像模版'}{assign var=admin_active value='cloud_templates'}{include file='admin/static_header.tpl'} + +

云镜像模版

模版按宿主机隔离,普通用户只能选择已导入的镜像。仅导入可信、支持 cloud-init 的 qcow2 镜像。

正在加载…

+
导入云镜像

校验值应从可信来源获取;不能从不可信镜像本身计算后当作可信校验。

已保存的模版
+{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/hosts/index.tpl b/web/resources/views/venix/admin/hosts/index.tpl index 37c7341c..4eb250f5 100644 --- a/web/resources/views/venix/admin/hosts/index.tpl +++ b/web/resources/views/venix/admin/hosts/index.tpl @@ -1,6 +1,30 @@ {assign var=admin_title value='宿主机设置'} {assign var=admin_active value='hosts'} {include file='admin/static_header.tpl'} -{include file='admin/hosts/preparation.tpl'} + +
+

宿主机设置

SSH 使用宿主机已有的 root 账号和私钥。先扫描并核对 SSH 主机指纹,再保存。私钥和口令加密存储,不会回显;后台会持续采集虚拟机指标。

+

正在加载…

+
+
添加宿主机
+
+
+
+
+
+
仅通过 HTTPS 提交;请勿将密钥粘贴到工单或日志。
+
加密保存,面板重启后可自动连接,后台采样不依赖网页登录。
+
+
+
+
+
只分配该地址池内未使用的地址;可输入 .113/28,后台会规范为 .112/28。
+
可与地址池 /28 不同,按服务商路由要求设置。
+
+
+
网关、网络地址和广播地址自动排除。请额外排除已有外部虚拟机占用的 IP。
+
+
+
+ {include file='admin/static_footer.tpl'} - diff --git a/web/resources/views/venix/admin/hosts/preparation.tpl b/web/resources/views/venix/admin/hosts/preparation.tpl deleted file mode 100644 index 040f0b38..00000000 --- a/web/resources/views/venix/admin/hosts/preparation.tpl +++ /dev/null @@ -1,20 +0,0 @@ -
-

宿主机设置

-

这是宿主机配置页面的准备版本。当前尚未接入虚拟化服务,不能保存配置或连接宿主机。

-

请勿在此输入私钥、密码或其他敏感凭据。以下禁用字段仅用于展示后续配置结构。

-
- - - - - - - - - - - - -
-

-
diff --git a/web/resources/views/venix/admin/shop/create.tpl b/web/resources/views/venix/admin/shop/create.tpl index f7e96d30..d15f9baa 100755 --- a/web/resources/views/venix/admin/shop/create.tpl +++ b/web/resources/views/venix/admin/shop/create.tpl @@ -1,7 +1,8 @@ {assign var=admin_title value='新增商品'}{assign var=admin_active value='shop'}{include file='admin/static_header.tpl'} -

新增云服务器套餐

仅配置套餐资源规格和价格。虚拟化服务接入前不会开通服务器。

返回商品列表
+

新增云服务器套餐

绑定宿主机后,用户可用余额购买开通。价格为本次开通价格,本版不含到期与续费。

返回商品列表
+
diff --git a/web/resources/views/venix/admin/shop/edit.tpl b/web/resources/views/venix/admin/shop/edit.tpl index 6015f770..768dd962 100755 --- a/web/resources/views/venix/admin/shop/edit.tpl +++ b/web/resources/views/venix/admin/shop/edit.tpl @@ -1,7 +1,8 @@ {assign var=admin_title value='编辑商品'}{assign var=admin_active value='shop'}{include file='admin/static_header.tpl'} -

编辑云服务器套餐

仅配置套餐资源规格和价格。虚拟化服务接入前不会开通服务器。

返回商品列表
+

编辑云服务器套餐

绑定宿主机后,用户可用余额购买开通。修改套餐不会改变已经开通的虚拟机。

返回商品列表
+
diff --git a/web/resources/views/venix/admin/shop/form_js.tpl b/web/resources/views/venix/admin/shop/form_js.tpl index 98f9e3f8..16836155 100755 --- a/web/resources/views/venix/admin/shop/form_js.tpl +++ b/web/resources/views/venix/admin/shop/form_js.tpl @@ -5,7 +5,29 @@ var submit = document.getElementById('shopFormSubmit'); var status = document.getElementById('shopFormStatus'); var toast = document.getElementById('shopFormToast'); - var fields = ['name','price','cpu_cores','memory_mib','bandwidth_mbps','disk_gib','status','stock','sort']; + var fields = ['name','host_id','price','cpu_cores','memory_mib','bandwidth_mbps','disk_gib','status','stock','sort']; + var hostSelect = document.getElementById('host_id'); + if (hostSelect) { + fetch('/api/v1/admin/hosts', {credentials: 'same-origin'}) + .then(function (response) { if (!response.ok) throw new Error('宿主机列表读取失败'); return response.json(); }) + .then(function (data) { + (data.items || []).forEach(function (host) { + if (!host.enabled) return; + var option = document.createElement('option'); + option.value = String(host.id); + option.textContent = host.name + (host.region ? ' · ' + host.region : ''); + hostSelect.appendChild(option); + }); + var selected = hostSelect.getAttribute('data-selected') || ''; + if (selected && !Array.from(hostSelect.options).some(function (option) { return option.value === selected; })) { + var unavailable = document.createElement('option'); + unavailable.value = selected; + unavailable.textContent = '已绑定宿主机不可用(ID ' + selected + ')'; + hostSelect.appendChild(unavailable); + } + hostSelect.value = selected; + }).catch(function (error) { setStatus(error.message + ',请先配置宿主机', 'is-error'); submit.disabled = true; }); + } function get(id) { var el = document.getElementById(id); diff --git a/web/resources/views/venix/admin/static_header.tpl b/web/resources/views/venix/admin/static_header.tpl index cdaef6d7..4e824a45 100644 --- a/web/resources/views/venix/admin/static_header.tpl +++ b/web/resources/views/venix/admin/static_header.tpl @@ -158,6 +158,10 @@
  • 宿主机设置
  • +
  • 云镜像模版
  • +
  • 救援模版
  • +
  • 虚拟机管理
  • +
  • 开通订单
  • diff --git a/web/resources/views/venix/auth/layout_header.tpl b/web/resources/views/venix/auth/layout_header.tpl index 58cf7096..27085c59 100644 --- a/web/resources/views/venix/auth/layout_header.tpl +++ b/web/resources/views/venix/auth/layout_header.tpl @@ -5,17 +5,18 @@ - + {$auth_title} | {$auth_app_name} - + +
    - + {$auth_app_name}