From cf192a5f3c9de7c190ec1c98d96d6a57a091685a Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Sun, 22 Nov 2026 02:15:29 +0300 Subject: [PATCH] Initialize standalone EzServer for macOS --- .gitignore | 5 + Package.swift | 12 ++ README.md | 42 +++++ Sources/EzDentStorage/PatientRecord.swift | 41 ++++ Sources/EzServerMac/LibraryAPI.swift | 149 +++++++++++++++ Sources/EzServerMac/main.swift | 219 ++++++++++++++++++++++ scripts/build-server.sh | 28 +++ server/extract-installshield.py | 67 +++++++ server/prepare.sh | 39 ++++ server/router.php | 43 +++++ server/run.sh | 35 ++++ 11 files changed, 680 insertions(+) create mode 100644 .gitignore create mode 100644 Package.swift create mode 100644 README.md create mode 100644 Sources/EzDentStorage/PatientRecord.swift create mode 100644 Sources/EzServerMac/LibraryAPI.swift create mode 100644 Sources/EzServerMac/main.swift create mode 100755 scripts/build-server.sh create mode 100644 server/extract-installshield.py create mode 100755 server/prepare.sh create mode 100644 server/router.php create mode 100755 server/run.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2fab09b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/_source/ +/.build/ +/.swiftpm/ +/dist/ +.DS_Store diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..438cc82 --- /dev/null +++ b/Package.swift @@ -0,0 +1,12 @@ +// swift-tools-version: 5.9 +import PackageDescription + +let package = Package( + name: "EzServerMac", + platforms: [.macOS(.v13)], + products: [.executable(name: "EzServerMac", targets: ["EzServerMac"])], + targets: [ + .target(name: "EzDentStorage"), + .executableTarget(name: "EzServerMac", dependencies: ["EzDentStorage"]) + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..e0614d7 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# EzServer для macOS + +Сборка для macOS 13 и новее, Intel и Apple Silicon. Распакуйте архив, откройте терминал в этой папке и запустите `./EzServerMac`. Сервер слушает `127.0.0.1:55005`. Переменная `EZSERVER_PORT` позволяет выбрать другой порт. + +```sh +curl http://127.0.0.1:55005/health +curl http://127.0.0.1:55005/api/v1/info/versions +curl 'http://127.0.0.1:55005/api/v1/info/versionsByName?name=3.0.6' +``` + +Информационные маршруты используют контракт EzWebServer из установщика EzServer 4.1.6. Версия API в установщике — 3.0.6. + +## Карточки и снимки + +Сервер может читать локальную библиотеку EzDent после создания первой карточки. Укажите её каталог и задайте токен из 32 или более печатных ASCII-символов. При такой конфигурации сервер перечитывает индекс при каждом запросе, поэтому изменения, сохранённые в EzDent, видны без перезапуска сервера. + +```sh +export EZSERVER_LIBRARY="$HOME/Library/Application Support/EzDent/Library" +export EZSERVER_TOKEN="$(openssl rand -hex 32)" +./EzServerMac & +curl -H "Authorization: Bearer $EZSERVER_TOKEN" \ + 'http://127.0.0.1:55005/mac/v1/patients?q=123&limit=50' +``` + +| GET | Результат | +| --- | --- | +| `/mac/v1/patients?q=...&offset=0&limit=50` | Поиск по имени или номеру карты. Лимит от 1 до 200. | +| `/mac/v1/patients/{patientID}` | Карточка и список вложений. Время импорта возвращается в ISO 8601. | +| `/mac/v1/patients/{patientID}/images/{imageID}` | Оригинал обычного снимка. | +| `/mac/v1/patients/{patientID}/images/{imageID}/slices/{number}` | Оригинал DICOM-среза. Нумерация файлов начинается с 1. | + +Карточки и снимки доступны по токену только по адресу loopback. Для этой библиотеки используется собственный интерфейс `/mac/v1` в режиме чтения. Вход Windows-клиента, схема PostgreSQL, Windows File Manager и Patch Manager пока не перенесены. Приложение EzDent для macOS по-прежнему открывает свою библиотеку локально. + +Формат библиотеки совпадает с форматом EzDent для macOS. При изменении формата в клиенте обновите модель в обоих репозиториях. + +## Сборка из репозитория + +`./scripts/build-server.sh` создаёт `dist/EzServerMac-universal.zip`. Нужны Swift и Xcode Command Line Tools. Готовый исполняемый файл работает без PHP, PostgreSQL и Windows. + +## Эксперимент с оригинальным PHP + +`server/prepare.sh` извлекает оригинальный EzWebServer из установщика с помощью Python 3, 7-Zip и unshield. Путь к установщику можно передать первым аргументом. Если команды называются иначе, укажите их через `EZSERVER_7ZIP` и `EZSERVER_UNSHIELD`. Для запуска информационных маршрутов через `server/run.sh` нужен PHP CLI с расширениями intl, mbstring и session. Совместимость оригинального веб-компонента с PHP на macOS пока не подтверждена. diff --git a/Sources/EzDentStorage/PatientRecord.swift b/Sources/EzDentStorage/PatientRecord.swift new file mode 100644 index 0000000..ea94f47 --- /dev/null +++ b/Sources/EzDentStorage/PatientRecord.swift @@ -0,0 +1,41 @@ +import Foundation + +package struct PatientRecord: Codable, Identifiable { + package let id: UUID + package var name: String + package var chartNumber: String + package var images: [PatientImage] + + package init(id: UUID, name: String, chartNumber: String) { + self.id = id + self.name = name + self.chartNumber = chartNumber + self.images = [] + } +} + +package struct PatientImage: Codable, Identifiable { + package let id: UUID + package let name: String + package let importedAt: Date + package var dicomCount: Int? + + package init(id: UUID, name: String, importedAt: Date, dicomCount: Int? = nil) { + self.id = id + self.name = name + self.importedAt = importedAt + self.dicomCount = dicomCount + } +} + +package enum LibraryPaths { + package static let index = "patients.json" + + package static func attachment(_ id: UUID, in directory: URL) -> URL { + directory.appendingPathComponent(id.uuidString) + } + + package static func slice(_ number: Int, of id: UUID, in directory: URL) -> URL { + attachment(id, in: directory).appendingPathComponent("slice-\(number).dcm") + } +} diff --git a/Sources/EzServerMac/LibraryAPI.swift b/Sources/EzServerMac/LibraryAPI.swift new file mode 100644 index 0000000..9d9a597 --- /dev/null +++ b/Sources/EzServerMac/LibraryAPI.swift @@ -0,0 +1,149 @@ +import CryptoKit +import EzDentStorage +import Foundation +import UniformTypeIdentifiers + +struct LibraryAPI { + struct Listing: Encodable { + let patients: [PatientSummary] + let total: Int + let offset: Int + let limit: Int + } + + struct PatientSummary: Encodable { + let id: UUID + let name: String + let chartNumber: String + let imageCount: Int + + init(_ patient: PatientRecord) { + id = patient.id + name = patient.name + chartNumber = patient.chartNumber + imageCount = patient.images.count + } + } + + struct File { + let handle: FileHandle + let bytes: Int + let contentType: String + let filename: String + } + + enum Result { + case listing(Listing) + case patient(PatientRecord) + case file(File) + case invalidRequest + case unauthorized + case notFound + case unavailable + } + + private let directory: URL + private let token: SHA256.Digest + + init?(environment: [String: String]) throws { + let path = environment["EZSERVER_LIBRARY"] + let secret = environment["EZSERVER_TOKEN"] + guard path != nil || secret != nil else { return nil } + guard let path, path.hasPrefix("/"), let secret, secret.utf8.count >= 32, + secret.utf8.allSatisfy({ (33...126).contains($0) }) else { + throw ConfigurationError.incomplete + } + + let directory = URL(fileURLWithPath: path, isDirectory: true).resolvingSymlinksInPath() + let index = directory.appendingPathComponent(LibraryPaths.index) + guard (try? index.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])) + .map({ $0.isRegularFile == true && $0.isSymbolicLink != true }) == true else { + throw ConfigurationError.invalidIndex + } + self.directory = directory + token = SHA256.hash(data: Data(secret.utf8)) + } + + func response(path: [String], query: [URLQueryItem], authorization: String?) -> Result { + guard let authorization, authorization.hasPrefix("Bearer ") else { return .unauthorized } + let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8)) + let mismatch = zip(candidate, token).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } + guard mismatch == 0 else { return .unauthorized } + + guard let index = try? openFile(directory.appendingPathComponent(LibraryPaths.index)) else { + return .unavailable + } + do { + defer { try? index.handle.close() } + guard index.bytes <= 32 * 1024 * 1024 else { return .unavailable } + let data = try index.handle.readToEnd() ?? Data() + let patients = try JSONDecoder().decode([PatientRecord].self, from: data) + + if path.isEmpty { return list(patients, query: query) } + guard let patientID = UUID(uuidString: path[0]), + let patient = patients.first(where: { $0.id == patientID }) else { return .notFound } + if path.count == 1 { return .patient(patient) } + + guard path.count == 3 || path.count == 5, path[1] == "images", + let imageID = UUID(uuidString: path[2]), + let image = patient.images.first(where: { $0.id == imageID }) else { return .notFound } + if path.count == 3, image.dicomCount == nil { + return .file(try openFile(LibraryPaths.attachment(image.id, in: directory), + filename: image.name)) + } + if path.count == 5, path[3] == "slices", let number = Int(path[4]), + let count = image.dicomCount, (1...4096).contains(count), (1...count).contains(number) { + return .file(try openFile(LibraryPaths.slice(number, of: image.id, in: directory), + filename: "slice-\(number).dcm", contentType: "application/dicom")) + } + return .notFound + } catch FileError.notFound { + return .notFound + } catch { + return .unavailable + } + } + + private func list(_ patients: [PatientRecord], query: [URLQueryItem]) -> Result { + let search = query.first { $0.name == "q" }?.value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let offset = query.first { $0.name == "offset" }?.value ?? "0" + let limit = query.first { $0.name == "limit" }?.value ?? "50" + guard let offset = Int(offset), offset >= 0, let limit = Int(limit), + (1...200).contains(limit), search.count <= 200 else { return .invalidRequest } + let selected = patients.filter { + search.isEmpty || $0.name.localizedStandardContains(search) + || $0.chartNumber.localizedStandardContains(search) + } + let start = min(offset, selected.count) + let results = selected.dropFirst(start).prefix(limit).map(PatientSummary.init) + return .listing(Listing(patients: results, total: selected.count, offset: offset, limit: limit)) + } + + private func openFile(_ url: URL, filename: String = "", contentType: String? = nil) throws -> File { + guard url.deletingLastPathComponent().resolvingSymlinksInPath().path + == url.deletingLastPathComponent().path else { throw FileError.notFound } + let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) + guard descriptor >= 0 else { throw FileError.notFound } + var metadata = stat() + guard fstat(descriptor, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG else { + close(descriptor) + throw FileError.notFound + } + let mime = UTType(filenameExtension: (filename as NSString).pathExtension)?.preferredMIMEType + return File(handle: FileHandle(fileDescriptor: descriptor, closeOnDealloc: true), + bytes: Int(metadata.st_size), contentType: contentType ?? mime ?? "application/octet-stream", + filename: filename) + } + + private enum ConfigurationError: LocalizedError { + case incomplete, invalidIndex + var errorDescription: String? { + switch self { + case .incomplete: return "Set EZSERVER_LIBRARY to an absolute path and EZSERVER_TOKEN to at least 32 printable ASCII characters." + case .invalidIndex: return "EZSERVER_LIBRARY must contain an EzDent patients.json index." + } + } + } + + private enum FileError: Error { case notFound } +} diff --git a/Sources/EzServerMac/main.swift b/Sources/EzServerMac/main.swift new file mode 100644 index 0000000..2606ea9 --- /dev/null +++ b/Sources/EzServerMac/main.swift @@ -0,0 +1,219 @@ +import Foundation +import Network + +private struct APIVersion: Encodable { + let name: String + let url: String + let supportStatus: String +} + +private struct VersionList: Encodable { + let errorCode = 0 + let serverName = "EzWebServer" + let currentVersionName = "3.0.6" + let currentStageVersionName = "0" + let versions: [APIVersion] +} + +private struct VersionMatch: Encodable { + let errorCode = 0 + let serverName = "EzWebServer" + let clientVersion: APIVersion + let serverVersion: APIVersion +} + +private final class LocalServer { + private let listener: NWListener + private let queue = DispatchQueue(label: "ezserver.loopback") + private let maxHeaderSize = 8192 + private let library: LibraryAPI? + + init(port: UInt16, library: LibraryAPI?) throws { + self.library = library + let parameters = NWParameters.tcp + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!) + listener = try NWListener(using: parameters) + } + + func start() { + listener.stateUpdateHandler = { state in + switch state { + case .ready: + if let port = self.listener.port { + print("EzServer Mac is listening on http://127.0.0.1:\(port)") + fflush(stdout) + } + case let .failed(error): + FileHandle.standardError.write(Data("Could not start EzServer: \(error)\n".utf8)) + exit(EXIT_FAILURE) + default: + break + } + } + listener.newConnectionHandler = { [weak self] connection in + guard let self else { connection.cancel(); return } + connection.start(queue: self.queue) + let timeout = DispatchWorkItem { [weak connection] in connection?.cancel() } + self.queue.asyncAfter(deadline: .now() + 5, execute: timeout) + self.receive(on: connection, buffer: Data(), timeout: timeout) + } + listener.start(queue: queue) + } + + private func receive(on connection: NWConnection, buffer: Data, timeout: DispatchWorkItem) { + connection.receive(minimumIncompleteLength: 1, maximumLength: maxHeaderSize - buffer.count) { + [weak self] data, _, complete, failure in + guard let self, failure == nil else { connection.cancel(); return } + var request = buffer + if let data { request.append(data) } + if let boundary = request.range(of: Data("\r\n\r\n".utf8)) { + timeout.cancel() + self.handle(request.prefix(upTo: boundary.lowerBound), on: connection) + } else if request.count >= self.maxHeaderSize { + self.send(["error": "Request header too large"], status: "431 Request Header Fields Too Large", on: connection) + } else if complete { + connection.cancel() + } else { + self.receive(on: connection, buffer: request, timeout: timeout) + } + } + } + + private func handle(_ request: Data, on connection: NWConnection) { + let lines = String(decoding: request, as: UTF8.self).components(separatedBy: "\r\n") + let requestLine = lines[0].split(separator: " ", omittingEmptySubsequences: false) + let hosts = lines.dropFirst().compactMap { line -> String? in + let parts = line.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) + guard parts.count == 2, parts[0].lowercased() == "host" else { return nil } + return parts[1].trimmingCharacters(in: .whitespaces) + } + guard requestLine.count == 3, ["HTTP/1.0", "HTTP/1.1"].contains(requestLine[2]), + requestLine[1].hasPrefix("/"), !requestLine[1].hasPrefix("//"), + let target = URLComponents(string: String(requestLine[1])), + hosts.count == 1, + hosts[0].range(of: #"\A(?:127\.0\.0\.1|localhost)(?::[0-9]{1,5})?\z"#, + options: [.regularExpression, .caseInsensitive]) != nil else { + send(["error": "Invalid request or host"], status: "400 Bad Request", on: connection) + return + } + guard requestLine[0] == "GET" else { + send(["error": "Only GET is supported"], status: "405 Method Not Allowed", + extraHeaders: "Allow: GET\r\n", on: connection) + return + } + + let segments = target.path.split(separator: "/").map(String.init) + if segments.starts(with: ["mac", "v1", "patients"]) { + let authorization = lines.dropFirst().compactMap { line -> String? in + let fields = line.split(separator: ":", maxSplits: 1) + guard fields.count == 2, fields[0].lowercased() == "authorization" else { return nil } + return fields[1].trimmingCharacters(in: .whitespaces) + } + serveLibrary(path: Array(segments.dropFirst(3)), query: target.queryItems ?? [], + authorization: authorization.count == 1 ? authorization[0] : nil, on: connection) + return + } + + let apiURL = "http://\(hosts[0])/api/v1" + let versions = [ + "1.0.0", "1.0.1", "1.1.0", "1.2.0", "1.3.0", "1.3.1", "1.3.2", "2.0.0", + "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6" + ].map { APIVersion(name: $0, url: apiURL, supportStatus: "supported") } + let listing = VersionList(versions: versions) + let path = target.path.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "/")) + switch path { + case "", "health": + send(["service": "EzServer Mac", "status": "ok"], on: connection) + case "api/v1/info/versions", "api/index.php/v1/info/versions": + send(listing, on: connection) + case "api/v1/info/versionsbyname", "api/index.php/v1/info/versionsbyname": + let name = target.queryItems?.first(where: { $0.name == "name" })?.value ?? "" + let match = versions.first { $0.name == name } ?? APIVersion(name: name, url: "", supportStatus: "unknown") + send(VersionMatch(clientVersion: match, serverVersion: versions[versions.count - 1]), on: connection) + default: + send(["error": "Route is unavailable in the macOS preview"], status: "404 Not Found", on: connection) + } + } + + private func serveLibrary(path: [String], query: [URLQueryItem], authorization: String?, + on connection: NWConnection) { + guard let library else { + send(["error": "Patient library is not configured"], status: "503 Service Unavailable", on: connection) + return + } + switch library.response(path: path, query: query, authorization: authorization) { + case let .listing(listing): + send(listing, on: connection) + case let .patient(patient): + send(patient, on: connection) + case let .file(file): + let safeName = file.filename.addingPercentEncoding(withAllowedCharacters: CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" + )) ?? "image" + let headers = responseHeaders(status: "200 OK", type: file.contentType, bytes: file.bytes, + extra: "Content-Disposition: attachment; filename*=UTF-8''\(safeName)\r\n") + connection.send(content: headers, completion: .contentProcessed { [weak self] error in + guard let self, error == nil else { connection.cancel(); return } + self.stream(file.handle, remaining: file.bytes, on: connection) + }) + case .unauthorized: + send(["error": "Bearer token required"], status: "401 Unauthorized", + extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection) + case .invalidRequest: + send(["error": "Invalid limit, offset or search query"], status: "400 Bad Request", on: connection) + case .notFound: + send(["error": "Patient or image not found"], status: "404 Not Found", on: connection) + case .unavailable: + send(["error": "Could not read patient library"], status: "503 Service Unavailable", on: connection) + } + } + + private func stream(_ handle: FileHandle, remaining: Int, on connection: NWConnection) { + guard remaining > 0, + let chunk = try? handle.read(upToCount: min(remaining, 64 * 1024)), + !chunk.isEmpty else { + try? handle.close() + connection.cancel() + return + } + connection.send(content: chunk, completion: .contentProcessed { [weak self] error in + guard let self, error == nil else { + try? handle.close() + connection.cancel() + return + } + self.stream(handle, remaining: remaining - chunk.count, on: connection) + }) + } + + private func responseHeaders(status: String, type: String, bytes: Int, extra: String) -> Data { + Data("HTTP/1.1 \(status)\r\nContent-Type: \(type)\r\nContent-Length: \(bytes)\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\(extra)\r\n".utf8) + } + + private func send(_ response: Response, status: String = "200 OK", + extraHeaders: String = "", on connection: NWConnection) { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + guard let body = try? encoder.encode(response) else { connection.cancel(); return } + let headers = responseHeaders(status: status, type: "application/json; charset=utf-8", + bytes: body.count, extra: extraHeaders) + connection.send(content: headers + body, completion: .contentProcessed { _ in + connection.cancel() + }) + } +} + +let servicePort = ProcessInfo.processInfo.environment["EZSERVER_PORT"] ?? "55005" +guard let port = UInt16(servicePort), port > 0 else { + FileHandle.standardError.write(Data("EZSERVER_PORT must be between 1 and 65535.\n".utf8)) + exit(EXIT_FAILURE) +} +do { + let library = try LibraryAPI(environment: ProcessInfo.processInfo.environment) + let server = try LocalServer(port: port, library: library) + server.start() + withExtendedLifetime(server) { dispatchMain() } +} catch { + FileHandle.standardError.write(Data("Could not start EzServer: \(error)\n".utf8)) + exit(EXIT_FAILURE) +} diff --git a/scripts/build-server.sh b/scripts/build-server.sh new file mode 100755 index 0000000..8501130 --- /dev/null +++ b/scripts/build-server.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +build_for_arch() { + local arch="$1" + local scratch=".build/server-$arch" + swift build -c release --product EzServerMac --arch "$arch" --scratch-path "$scratch" >&2 || return + swift build -c release --arch "$arch" --scratch-path "$scratch" --show-bin-path +} + +arm64_bin="$(build_for_arch arm64)" +x86_64_bin="$(build_for_arch x86_64)" +mkdir -p dist +stage="$(mktemp -d dist/.EzServer.XXXXXX)" +trap 'rm -rf "$stage"' EXIT +package="$stage/EzServerMac" +mkdir "$package" +binary="$package/EzServerMac" +xcrun lipo -create "$arm64_bin/EzServerMac" "$x86_64_bin/EzServerMac" -output "$binary" +xcrun lipo "$binary" -verify_arch arm64 x86_64 +codesign --force --sign - "$binary" +codesign --verify --strict "$binary" +cp README.md "$package/README.md" +ditto -c -k --keepParent "$package" "$stage/EzServerMac-universal.zip" +mv "$stage/EzServerMac-universal.zip" dist/EzServerMac-universal.zip +printf '%s\n' "$PWD/dist/EzServerMac-universal.zip" diff --git a/server/extract-installshield.py b/server/extract-installshield.py new file mode 100644 index 0000000..896721b --- /dev/null +++ b/server/extract-installshield.py @@ -0,0 +1,67 @@ +"""Extract the EzServer cabinet records from a 7-Zip InstallShield overlay.""" +from pathlib import Path +import shutil +import sys + +CABINETS = {b"data1.hdr", b"data1.cab", b"data2.cab"} + + +def read_field(stream): + value = bytearray() + for _ in range(1024): + byte = stream.read(1) + if byte == b"\0": + return bytes(value) + if not byte: + break + value.extend(byte) + raise ValueError("Incomplete InstallShield record") + + +def extract(overlay, output): + missing = CABINETS.copy() + with overlay.open("rb") as stream: + while missing: + name = read_field(stream) + read_field(stream) # Path on the installation media. + read_field(stream) # File version. + size = int(read_field(stream)) + end = stream.tell() + size + if size < 0 or end > overlay.stat().st_size: + raise ValueError("Invalid InstallShield record size") + if name in missing: + with (output / name.decode("ascii")).open("wb") as destination: + remaining = size + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("Truncated cabinet") + destination.write(chunk) + remaining -= len(chunk) + missing.remove(name) + stream.seek(end) + + +def stage_web_service(extracted, runtime): + source = extracted / "www" / "ezwebserver" / "src" + destination = runtime / "www" / "ezwebserver" / "src" + for folder in ("application", "public", "vendor"): + shutil.copytree( + source / folder, + destination / folder, + ignore=shutil.ignore_patterns( + "*.exe", "*.dll", "*.bat", "*.cmd", "*.msi", "dbconfig.ini", "config_base.ini" + ), + ) + for name in ("application/cache/sessions", "application/logs"): + (destination / name).mkdir(parents=True, exist_ok=True) + shutil.copy2(extracted / "webapps" / "index.html", runtime / "index.html") + + +if __name__ == "__main__": + if sys.argv[1] == "cabinet": + extract(Path(sys.argv[2]), Path(sys.argv[3])) + elif sys.argv[1] == "stage": + stage_web_service(Path(sys.argv[2]), Path(sys.argv[3])) + else: + raise SystemExit("Unknown extraction operation") diff --git a/server/prepare.sh b/server/prepare.sh new file mode 100755 index 0000000..04d74f1 --- /dev/null +++ b/server/prepare.sh @@ -0,0 +1,39 @@ +#!/bin/bash +set -euo pipefail +umask 077 + +server_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +project_dir="$(dirname "$server_dir")" +installer="${1:-$project_dir/_source/EzServer V4.1.6 Setup.exe}" +runtime="${EZSERVER_RUNTIME:-$project_dir/.build/ezserver-macos/runtime}" +unshield="${EZSERVER_UNSHIELD:-unshield}" +archive_tool="${EZSERVER_7ZIP:-7z}" + +if [[ ! -f "$installer" ]]; then + printf 'EzServer installer not found: %s\n' "$installer" >&2 + exit 1 +fi +for dependency in "$unshield" "$archive_tool" python3; do + if ! command -v "$dependency" >/dev/null; then + printf 'Missing extraction tool: %s\n' "$dependency" >&2 + exit 1 + fi +done +if [[ -e "$runtime" ]]; then + printf 'EzServer runtime already exists: %s\n' "$runtime" >&2 + exit 1 +fi + +parent="$(dirname "$runtime")" +mkdir -p "$parent" +stage="$(mktemp -d "$parent/.prepare.XXXXXX")" +trap 'rm -rf "$stage"' EXIT +"$archive_tool" e -y "-o$stage" "$installer" '[0]' >/dev/null +python3 "$server_dir/extract-installshield.py" cabinet "$stage/[0]" "$stage" +"$unshield" -g EzWebServer_Install -d "$stage/extracted" x "$stage/data1.cab" > "$stage/extract.log" +mkdir "$stage/runtime" +python3 "$server_dir/extract-installshield.py" stage "$stage/extracted/EzWebServer_Install" "$stage/runtime" +test -f "$stage/runtime/www/ezwebserver/src/public/api/index.php" +test -f "$stage/runtime/www/ezwebserver/src/vendor/autoload.php" +mv "$stage/runtime" "$runtime" +printf '%s\n' "$runtime" diff --git a/server/router.php b/server/router.php new file mode 100644 index 0000000..7b3e265 --- /dev/null +++ b/server/router.php @@ -0,0 +1,43 @@ + $message]); +} + +header('Cache-Control: no-store'); +$host = $_SERVER['HTTP_HOST'] ?? ''; +if (!preg_match('/\A(?:127\.0\.0\.1|localhost)(?::[0-9]{1,5})?\z/i', $host)) { + failRequest(400, 'Use a loopback host'); + return; +} +if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') { + header('Allow: GET'); + failRequest(405, 'Only GET is supported'); + return; +} + +$runtime = getenv('EZSERVER_RUNTIME'); +$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH); +if ($path === '/') { + header('Content-Type: text/html; charset=utf-8'); + readfile($runtime . '/index.html'); + return; +} + +if (!preg_match('~\A/api(?:/index\.php)?(?:/v1/info/(?:versions|versionsbyname))?/?\z~i', $path ?? '')) { + failRequest(404, 'Route is unavailable in the macOS preview'); + return; +} + +$public = $runtime . '/www/ezwebserver/src/public'; +$_SERVER['DOCUMENT_ROOT'] = $public; +$_SERVER['SCRIPT_FILENAME'] = $public . '/api/index.php'; +$_SERVER['SCRIPT_NAME'] = '/api/index.php'; +$_SERVER['PHP_SELF'] = '/api/index.php'; +$_SERVER['CI_ENV'] = 'production'; +chdir($public . '/api'); +require $_SERVER['SCRIPT_FILENAME']; diff --git a/server/run.sh b/server/run.sh new file mode 100755 index 0000000..5dada2a --- /dev/null +++ b/server/run.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -euo pipefail +umask 077 + +server_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +project_dir="$(dirname "$server_dir")" +runtime="${EZSERVER_RUNTIME:-$project_dir/.build/ezserver-macos/runtime}" +php="${EZSERVER_PHP:-php}" +port="${EZSERVER_PORT:-55005}" + +if [[ ! -f "$runtime/www/ezwebserver/src/public/api/index.php" ]]; then + printf '%s\n' 'Prepare the EzServer runtime with server/prepare.sh first.' >&2 + exit 1 +fi +if ! command -v "$php" >/dev/null; then + printf '%s\n' 'PHP CLI is required. Install PHP or set EZSERVER_PHP to its executable.' >&2 + exit 1 +fi +if ! [[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] || (( port > 65535 )); then + printf '%s\n' 'EZSERVER_PORT must be between 1 and 65535.' >&2 + exit 1 +fi + +"$php" -r ' +foreach (["intl", "mbstring", "session"] as $extension) { + if (!extension_loaded($extension)) { + fwrite(STDERR, "Missing PHP extension: " . $extension . PHP_EOL); + exit(1); + } +} +' +export EZSERVER_RUNTIME="$(cd "$runtime" && pwd)" +mkdir -p "$EZSERVER_RUNTIME/empty" +exec "$php" -d display_errors=0 -d expose_php=0 \ + -S "127.0.0.1:$port" -t "$EZSERVER_RUNTIME/empty" "$server_dir/router.php"